Class, Constructors and Inheritance2 min read

What is a Class?
Class in OOP is a representation of real world object or better to say a blueprint for creating objects. When creating an object in OOP we are using Class. So, class is a blueprint and objects are instances of a Class in an application.
Each class may be consisted of several properties or methods.
i.e.:
public class Animal { public int MaxSpeed { get; set; } public int NumberOfHands{ get; set; } public int NumberOfLegs{ get; set; } public void Run (); public void Crawl(); } var dog = new Animal(); dog.MaxSpeed = 15; dog.NumberOfHands= 0; dog.NumberOfLegs= 4; dog.Run(); dog.Crawl();
As you can see above, we have generally an animal with some default properties and then we create an instance of that class, in this case concrete object is a dog, with it’s own properties and methods defined by Animal Class. So, we might have unlimited number of instances of that class (lion, cat, mouse…).
Naming conventions?
In C# we use two type of naming conventions:
- Pascal Case
- camel Case
PascalCase is used for property names and methods, while camelCase is used for constructor or method parameters.
Constructors and Inheritance?
There are two things to remember regarding Base Class Constructors:
- Base Class Constructros are always executed first
- Base Class Constructors are not inherited
i.e.:
public class CellPhone { private string _serialNumber; public CellPhone(string serialNumber){ _serialNumber = serialNumber; Console.WriteLine("CellPhone serial number is {0}", serialNumber); } } // derived class public class IPhone: CellPhone { public IPhone(string serialNumber): base(serialNumber){ // now, to access serial number property we need to add base // it's basically sending argument(s) to a method called base which sends args to // CellPhone constructor Console.WriteLine("IPhone serial number is {0}", serialNumber); } } var iPhone = new IPhone("serial12345"); // output: IPhone serial number is serial12345 and CellPhone serial number is serial12345.
This way we send args to base class if we need to instantiate some props during object creation.
Summary:
As you can see, using inheritance and base class it is very easy to send arguments which are needed during object creation.
Imagine “: base(args)” as a method of a base class which receives parameter or parameters. This way we may set some initial property values which are needed for our base class. Best example is when using DbContext class in repository pattern.

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like In my latest Youtube video,…

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Let me write today about…