जगदीश खोलिया: How to call a specific base constructor in C#?

Friday, November 25, 2011

How to call a specific base constructor in C#?

How to call a specific base constructor in C#?
What is a Constructor? - It is a method that gets invoked when an instance of a class is created. In case a class has plenty of constructors, i.e. there are plenty of overloaded constructors, in such a scenario, it is still possible to invoke a specific base constructor. But there is a special way, as explicit calls to a base constructor is not possible in C#. See code below:
C# Example
public class dotnetClass
{
public dotnetClass()
{
// The constructor method here
}
// Write the class members here
}

// below shows how to overload a constructor
public class dotnetClass
{
public dotnetClass()
{
// This constructor is without a parameter
// Constructor #1
}

public dotnetClass(string name)
{
// This constructor has 1 parameter.
// Constructor #2

}
}
This constructor gets executed when an object of this class is instantiated. This is possible in C#. Calling a specific constructor will depend on how many parameters, and what parameters match a specific constructor. Note that a compile time error may get generated when 2 constructors of the same signature are created.

We may make use of the this keyword and invoke a constructor. See code example below.
this("some dotnet string");
//This will call Constructor #2 above
What is the use of the base keyword. Suppose we have a derived class named dotnetderivedclass. If this derived class is to invoke the constructor of a base class, we make use of the base keyword. See code example below on how to use a base keyword to invoke the base class constructor.
public class dotnetClass
{
public dotnetClass()
{
// The 1st base class constructor defined here
}

public dotnetClass(string Name)
{
// The 2nd base class constructor defined here
}
}

public class dotnetderivedclass : dotnetClass
// A class is being inherited out here
{
public dotnetderivedclass()
{
// dotnetderivedclass 1st constructor defined here
}

public dotnetderivedclass(string name):base(name)
{
// dotnetderivedclass 2nd constructor defined here
}
}
Note that we have used the base keyword in the sample code above. The sequence of execution of the constructors will be as follows:
public dotnetClass() method -> public dotnetderivedclass() method

The above sequence triggers when there is no initializer to the base class, and thus it triggers the parameterless base class constructor. The other base class constructor may also get invoked when we pass a parameter while defining it.

No comments: