web analytics

Understanding C# Default Constructor

Options

codeling 1602 - 6666
@2016-01-01 11:03:15

In C#, if you don't specify any constructors at all, a default constructor is provided by the compiler. This default constructor is a parameterless constructor with no body, which calls the parameterless constructor of the base class. In other words:

public class MyClass
{
    int someMemberVariable;
}

... is exactly equivalent to:

public class MyClass
{
    int someMemberVariable;
               
    public MyClass() : base()
    {
    }
}

This means that if the base class has no accessible parameterless constructor (including a default one), you get a compile-time error if the derived class doesn't have any constructors - because the default constructor will implicitly try to call a parameterless constructor from the base type.

If the class is abstract, the default constructor provided has protected accessibility; otherwise it has public accessibility.

If you define a contructor in your C# class, for example, the following class has a single constructor, which takes an int as a parameter, and prints that int's value to the console.

public class MyClass
{
    public MyClass (int x)
    {
        Console.WriteLine (x);
    }
}

Following from the previous section, there's something else going on here, which is hidden by the compiler. The above is actually equivalent to:

public class MyClass
{
    public MyClass (int x) : base()
    {
        Console.WriteLine (x);
    }
}

Note the base() bit. That's saying the default constructor should be invoked before any of the rest of the code in the constructor runs.

You can also calls another constructor from this class, using the this (...) syntax.

public class MyBaseClass
{
    public MyBaseClass (int x) : base() //Invoke the default constructor in object
    {
        Console.WriteLine ("In the base class constructor taking an int, which is "+x);
    }
}

public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass () : this (5) // Invoke the constructor taking an int
    {
        Console.WriteLine ("In the derived class parameterless constructor.");
    }
}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com