There are two types of inheritence implemented in C#. Implementation Inheritence and Interface Inheritence.

Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and functions. With implementation inheritance, a derived type adopts the base type’s implementation of each function, unless it is indicated in the definition of the derived type that a function implementation is to be overridden. This type of inheritance is most useful when you need to add functionality to an existing type, or where a number of related types share a significant amount of common functionality.

Interface inheritance means that a type inherits only the signatures of the functions but does not inherit any implementations. This type of inheritance is most useful when you want to specify that a type makes certain features available. Interface inheritance is often regarded as providing a contract: By deriving from an interface, a type is guaranteed to provide certain functionality to clients.

Imp: C# doesnot implement Multiple Inheritence i.e. you cannot inherit a class from more than one class.

By declaring a base class function as virtual, you allow the function to be overridden in any derived classes.

class MyBaseClass
{
   public virtual string VirtualMethod()
   {
      return “This method is virtual and defined in MyBaseClass and can be overridden in                   derievd class”;
   }
}

You use the override keyword when you write a new implementation of the virtual method in the derieved class.

public override string VirtualMethod() //this is the method which is overriden.

Neither member fields nor static functions can be declared as virtual.

Hiding Methods

If a method with the same signature is declared in both base and derived classes, but the methods are not declared as virtual and override, respectively, then the derived class version is said to hide the base class version.In these situations, C# generates a compilation warning. That reminds you to use the new keyword to declare that you intend to hide a method.

you can use the base.<MethodName>() syntax to call any method in the base class .

C# allows both classes and functions to be declared as abstract. An abstract class cannot be instantiated, whereas an abstract function does not have an implementation, and must be overridden in any non-abstract derived class. Obviously, an abstract function is automatically virtual (although you don’t need to supply the virtual keyword; doing so results in a syntax error).

C# allows classes and methods to be declared as sealed. In the case of a class, this means that you can’t inherit from that class. In the case of a method, this means that you can’t override that method.

Constructors in the hierarchy

If all the classes in the hierarchy have only default constructors then when u instantiate a class the control goes to the constructor of its immediate base class from there it goes to its immediate base class…like that till it reaches System.Object. Since System.Object doesnot have any base class…its constructor is executed…then its next derieved class’ cons is exec…till it reaches the cons of the class to be instantiated.

When you write your own constructors…stick to this principle.The base and this keywords are the only keywords allowed in the line that calls another constructor. Anything else causes a compilation error. Also note that only one other constructor can be specified.

We’ll take an example to understand this:

We have class called Employee it just has a field indicating the EmpId

class Employee
{
      private string empId;
      public Employee()
     {
      }
}

Then you have a class called ContractEmployee which is inherited from Employee and has an extra field of number of contract months.
class ContractEmployee: Employee
{
       private int contractMonths;
       public ContractEmployee():base()
      {
      }
}

In the above case when the class ContractEmployee is instantiated then the default cons of its base class is called and goes upto Object class. If you want to instantiate the employee field with employee id i.e if the user has to produce the employee id of the new emp while creating the class itself then the constructor of the Employee class takes a parameter and takes the following form

class Employee
{
      private string empId;
      public Employee(string id)
     {
          this.empId = id;
     }
}

Now when you instantiate the derieved class i.e the ContractEmployee class then you have to supply name to the emp…but that field is a private member of the base class. So what you have is sth like this:

class ContractEmployee: Employee
{
       private int contractMonths;
       public ContractEmployee(string id):base(id)
      {
      }
}

The derieved class has no way to implement this but the base class can do that so what the former does is to pass on the parameter to the base class cons.

Now the req is that the emp who referred to the conractemp should be saved in a field of referrer.

class ContractEmployee: Employee
{
       private int contractMonths;
       private string referrer;
       public ContractEmployee(string id,string refr):base(id)
      {
            this.referrer = refr
      }
}

But there may be some contract emp who have no referrers for them there would be no referrers. For them you should have a one parameter cons.Note how this is implemented….the derieved class now has two constructors with two parameters.

class ContractEmployee: Employee
{
       private int contractMonths;
       private string referrer;
       public ContractEmployee(string id,string refr):base(id)
      {
            this.referrer = refr
      }
     public ContractEmployee(string id):this(id,”none”)
      {      
      }

}

thi is how more than one constructors are implemented.When a contract emp with no ref is instantiated then cons with one param is called which in turns call the cons with 2 params giving the referrer as “none” then the base classes single param cons is called.

The syntax for a constructor is tht you declare a method that has the same name as the containing class and that does not have any return type:
public class MyClass
{
    public MyClass()
  {
  }
  // rest of class definition

if you don’t supply any constructor, the compiler will just make up a default one for you behind the scenes. It’ll be a very basic constructor that just initializes all the member fields by zeroing them out (null reference for reference types, zero for numeric data types, and false for bools).you can provide as many overloads to the constructor as you want, provided they are clearly different in signature.however, that if you supply any constructors that take parameters, the compiler will not automatically supply a default one. This is done only if you have not defined any constructors at all.

You can specify access specifiers for constructors. If you specify a constructor as private then it is impossible for that class to get instantiated. It is useful in couple of occasions such as:

  • If your class serves only as a container for some static members or properties and therefore should never be instantiated

  • If you want the class to only ever be instantiated by calling some static member function (this is the so-called class factory approach to object instantiation)

  • Static Constructor

    Static Constructor is the one that can be executed only once. It is exec only one time  unlike instance constructors which are exec for every instance.One reason for writing a static constructor is if your class has some static fields or properties that need to be initialized from an external source before the class is first used.

    The .NET runtime makes no guarantees about when a static constructor will be executed, so you should not place any code in it that relies on it being executed at a particular time (for example, when an assembly is loaded). Nor is it possible to predict in what order static constructors of different classes will execute. However, what is guaranteed is that the static constructor will run at most once, and that it will be invoked before your code makes any reference to the class. In C#, the static constructor usually seems to be executed immediately before the first call to any member of the class.

    the static constructor cannot ever take any parameters, and there can only be one static constructor for a class. It should also be obvious that a static constructor can only access static members, not instance members, of the class.It can’t hav any access modifiers.Note that it is possible to have a static constructor and a zero-parameter instance constructor defined in the same class.Note that if you have more than one class that has a static constructor, the static constructor that will be executed first is undefined.

    public MyClass(string description) : this(model, 4)
       {
       }

    the this keyword allows us to call the constructor in the same class with the matchin signature.It will be the first constructor to get execueted and then the remaining code of the callin constructor is executed. If you use base keyword then it will call the matchin constructor of the base class.

    Syntax for the properties is
    [modifier] return_type PropertyName
    {
             get
            {
                  //return value
            }
             set
           {
             //do set the val here…
           }
    }

    The get accessor takes no parameters and must return the same type as the declared property. You should not specify any explicit parameters for the set accessor either, but the compiler assumes it takes one parameter, which is of the same type again, and which is referred to as value.
    It is possible to create a read-only property by simply omitting the set accessor from the property definition.
    It is similarly possible to create a write-only property by omitting the get accessor.

    The get and set accessor can have different access modifiers

    public string ExProperty
    {
             get
            {
                  //return value
            }
             private set
           {
             //do set the val here…
           }
    }

    Here the set accessor has private accessibility. Atleast one should have access modifier of the Property. Here if the scope of get were to be Protected then it would have resulted in a compile error.

    The syntax for declaring a method is

    [modifiers] return_type MethodName([parameters])
    {
          //Method body…
    }

    Arguments can in general be passed into methods by reference or by value.When a variable is passed by reference, the called method gets the actual variable – so any changes made to the variable inside the method persist when the method exits. On the other hand, if a variable is passed by value, the called method gets an identical copy of the variable – which means any changes made are lost when the method exits.

    Passing variables by value is the default. You can, however, force value parameters to be passed by reference. To do so, you use the ref keyword.

    int exMethod(int[] intarr, ref int i)
    {
           intarr[0] = 10; // The change to i will persist after exMethod() exits.
           i = 20;
    }

    Adding the ref keyword in C# serves the same purpose as using the & syntax in C++ to specify passing by reference.Any variable must be initialized before it is passed into a method, whether it is passed in by value or reference.

    You need to initialise all the variables before using them and this is valid for parameters.. to avoid doing that we can use out keyword to send in the var that is not yet initialised

    static void exMethod(out int i)
    {
       p= 10;
    }

    public static int Main()
    {
       int p; // note how i is declared but not initialized.
       exMethod(out p);
       Console.WriteLine(p);
       return 0;
    }

    Overloading

    C# supports method overloading – several versions of the method that have different signatures (that is, the name, number of parameters, and parameter types).

    C# does not support default parameters in the way that, say, C++ or Visual Basic does.

    The following care should be taken for overloading methods:

  • It is not sufficient for two methods to differ only in their return type.

  • It is not sufficient for two methods to differ only by virtue of a parameter having been declared as ref or out.

  •  A Class and an Object are like egg and hen… which would have come out first?… The class is a blue print of an object and we can design a class only if we hav the object with us…

    Class is a template for an object.. you instantiate a class to create an object its like you give flesh and skin to a skeleton… :-)

    Structs differ from classes in the way that they are stored in memory and accessed (classes are reference types stored in the heap, structs are value types stored on the stack), and in some of the features (for example, structs don’t support inheritance).

    For both classes and structs, you use the keyword new to declare an instance: This keyword creates the object and initializes it.

    Data members are those members that contain the data for the class – fields, constants, and events.Data members can be either static (associated with the class as a whole) or instance (each instance of the class has its own copy of the data).

    Fields are any variables associated with the class.

    Function members are those members that provide some functionality for manipulating the data in the class. They include methods, properties, constructors, finalizers, operators, and indexers.

    In Visual Basic, C, and C++, you could define global functions that were not associated with a particular class. This is not the case in C#. As noted earlier, in C# every function must be associated with a class or struct.

    official C# terminology does in fact make a distinction between functions and methods. In this terminology, the term “function member” includes not only methods, but also other nondata members of a class or struct. This includes indexers, operators, constructors, destructors, and also – perhaps somewhat surprisingly – properties. These are contrasted with data members: fields, constants, and events.

    Structs are similar to Classes but are more useful where we just need to group some data and dont require all the flexibility of the classes thus reducing the performance head.

    They differ from classes in the following ways:

    • Structs are value types, not reference types. This means they are stored either in the stack or inline (if they are part of another object that is stored on the heap) and have the same lifetime restrictions as the simple data types.

    • Structs do not support inheritance.

    • There are some differences in the way constructors work for structs. In particular, the compiler always supplies a default no-parameter constructor, which you are not permitted to replace.

    • With a struct, you can specify how the fields are to be laid out in memory. 

    Structs follow the same rules as any other data type: everything must be initialized before use.

    You can define constructors for structs in exactly the same way that you can for classes, except that you are not permitted to define a constructor that takes no parameters.

    struct Dimensions
    {
       public double Length = 1;       // error. Initial values not allowed
       public double Width = 2;        // error. Initial values not allowed
    }

    Partial Classes are classes which span across multiple files…which on compilation become one…this helps if more people work on a single class..

    if you don’t specify a base class when you define a class, the compiler will automatically assume that it derives from Object. It means that in all you classes you also have the methods which are present in the Object class. The diff methods in the Object class are:

    string ToString()
     public virtual
     Returns a string representation of the object
     
    int GetHashCode()
     public virtual
     Used if implementing dictionaries (hash tables)
     
    bool Equals(object obj)
     public virtual
     Compares instances of the object for equality
     
    bool Equals(object objA, object objB)
     public static
     Compares instances of the object for equality
     
    Type GetType()
     Public
     Returns details of the type of the object
     
    object MemberwiseClone()
     Protected
     Makes a shallow copy of the object
     
    void Finalize()
     protected virtual
     This is the .NET version of a destructor