An Intro to constructors in C #

Source: Internet
Author: User
Tags constructor inheritance modifier
This is a article on constructors in C # for the beginner level programmers. It covers simple constructors, constructors overloading, behaviour of constructors in inheritance, constructor chaining D Static Constructors. At the "End", it contains the general FAQs about constructors.



Introduction
Broadly speaking, a constructor is a method in the class which gets executed when it object is created. Usually, we put the initialization code in the constructor. Writing a constructor in the class are damn simple, have a look at the following sample:

public class Mysampleclass
{
Public Mysampleclass ()
{
This is the constructor method.
}
Rest of the class members goes here.
}
When the "This" class is instantiated, this constructor'll be executed. Something like this:

Mysampleclass obj = new Mysampleclass ()
At this time the code in the constructor'll//be executed
Constructor overloading
C # supports overloading of constructors, that means, we can have constructors with different sets of parameters. So, our class can is like this:

public class Mysampleclass
{
Public Mysampleclass ()
{
This is the No. parameter constructor method.
The constructor
}

Public mysampleclass (int age)
{
This is the constructor with one parameter.
Second Constructor

}

Public Mysampleclass (int age, String Name)
{
This is the constructor with two parameters.
Third constructor
}

Rest of the class members goes here.
}
So, here's the call to the "constructor now depends" on the way and you instantiate the object. For example:

Mysampleclass obj = new Mysampleclass ()
At this time the code of no parameter
Constructor (constructor) 'll be executed

Mysampleclass obj = new Mysampleclass (12)
At this time the code of one parameter
Constructor (Second constructor) would be
Executed.
The call to the constructors are completely governed by the rules of overloading here.

Calling constructor from another constructor
Can always make a call to one constructor from within another. Say, for example:

public class Mysampleclass
{
Public Mysampleclass (): This (10)
{
This is the No. parameter constructor method.
The constructor
}

Public mysampleclass (int age)
{
This is the constructor with one parameter.
Second Constructor
}
}
Very, let us-what is this syntax:

Public Mysampleclass (): This (10)
Here, this is refers to same class, so when we say this (we), we actually mean execute the public mysampleclass (int age) Metho D. The above way of the calling of the is called initializer. We can have at the most one initializer of this way in the.

Another thing which we must know is the execution sequence., i.e method would be which when. Here, if I instantiate the object as:

Mysampleclass obj = new Mysampleclass ()
Then the Code of Public mysampleclass (int age) would be executed before the code of Mysampleclass (). So, practically's definition of the method:

Public Mysampleclass (): This (10)
{
This is the No. parameter constructor method.
The constructor
}
is equivalent to:

Public Mysampleclass ()
{
Mysampleclass (10)
This is the No. parameter constructor method.
The constructor
}
Note:above (just Above this line) the code is mentioned there the for pure analogy and'll not compile. The intention is the execution if initializers are used.

We cannot make a explicit call to the constructors in C #, treating them as if any, for example:statement m Ysampleclass in the above code would not work. The only way can be call one constructor from another is through initializers.

For the "vb.net programmers:you can make" to another constructor of the same class by the syntax me.new (param list ), but it should be the ' the ' ' The ' the ' the ' your calling constructor method. So ultimately, the code of the "called constructor runs prior to" the Code of the calling constructor, which is same as Init Ializers here.

This is the only this and base (we'll, it further) keywords are allowed in initializers, and the other method calls would raise An error.

This is sometimes called constructor chaining.

Huff ... Simple thing made tough, but this are how it is. Anyway, let us proceed further.

Behavior of constructors in inheritance
Let us-Create the inherited class.

public class MyBaseClass
{
Public MyBaseClass ()
{
Code for the constructor class
}

public mybaseclass (int age)
{
Code for Second Base class constructor
}

Other class members goes
}

public class Myderivedclass:mybaseclass
This I am inheriting the class here.
{
Public Myderivedclass ()
{
Code for the "the" Myderivedclass constructor.
}

Public myderivedclass (int age): Base (age)
{
Code for the Second Myderivedclass constructor.
}

Other class members goes
}
Now, what is the execution sequence here:

If I Create the object of the derived class as:

Myderivedclass obj = new Myderivedclass ()
Then the sequence of execution would be:

Public MyBaseClass () method.
And then public Myderivedclass () method.
Note:if we don't provide initializer referring to the base class constructor then it executes the no parameter construct Or of the base class.

Note One thing here:we are is not making any explicit call to the constructor of base class neither by initializer nor by th E base keyword, but it is still executing. This is the normal behavior of the constructor.

If I Create an object of the derived class as:

Myderivedclass obj = new Myderivedclass (15)
Then the sequence of execution would be:

public mybaseclass (int age) method
And then public myderivedclass (int age) method
Here, the new keyword base has come into the picture. This is refers to the base class of the current class. So, here's it refers to the mybaseclass. And base refers to the call to MyBaseClass (int age) method.

Also Note the "Usage of age variable in" syntax:public myderivedclass (int age): base (age). [Understanding it is left to the reader].

Private Constructors
Private constructors, the constructors with the ' private ' access modifier, are a bit special case. It is because we can neither create the object of class, nor can we inherit the class with only private constructors. But Yes, we can have the "set of public constructors along" with the "private constructors in" class and the public constr Uctors can access the private constructors from within the class through constructor chaining.

Say For example, the My class are something like this:

public class MyClass
{
Private MyClass ()
{
Console.WriteLine ("This is no parameter constructor");
}

public MyClass (int var): this ()
{
Console.WriteLine ("This is one parameter constructor");
}
Other class methods goes
}

Then We can create the object of this class by the statement:

MyClass obj = new MyClass (10);
The above statement would work fine, but the statement

MyClass obj = new MyClass ();
Would raise an error: ' Constructors.MyClass.MyClass () ' are inaccessible due to it protection level

It is possible to have the class with only the private constructors. But Yes as I said, such class can neither be instantiated nor to be inherited. If we try to inherit the class with only private constructors then we'll get the same error as above. Also recall, once you provide constructor from your side the compiler won't add the No-parameter public constructor to Your class.

So, one of the usage scenarios of such class could be–when you have only static members in the class and don ' t nee D to instantiate it.

Phew ... lost ... Anything left in constructors? Yes, Static Constructors. ha!! Now, what are they? Let us ...

Static Constructors
This is the new concept introduced in C #. By new here, I mean that it is wasn't available for the C + + developers. This is a special constructor and gets called before the The class. The time of execution cannot was determined, but it is definitely before the "the" the "the" the "the" the "the" The Time O F Loading the assembly.

The syntax of writing the static constructors is also damn simple. Here it is:

public class MyClass
{
Static MyClass ()
{
Initialization code goes here.
Can only access is static.
}
Other class methods goes
}
Notes for Static Constructors:

There can is only one of the static constructor in the class.
The static constructor should be without parameters.
It can only access the static members of the class.
There should is no access modifier in static constructor definition.
Ok Fine, all the above points are fine, but why are it like that? Let-us go step is here.

Firstly, the call to the "static" is made by the CLR and not by the "object", so we did not need to have the access Modi Fier to it.

Secondly, it is going to being called by CLR, who can pass the parameters to it, if required. So we cannot have parameterized static constructor.

Thirdly, non-static members of the class are specific to the object instance. So-static constructor, if allowed to work on non-static members, would reflect the changes in all the object instances, WHI The CH is impractical. So-static constructor can access only static members of the class.

Fourthly, overloading needs the two methods to is different in terms of methods definition, which your cannot do with Stati C constructors, so can have at the most one static constructor in the class.

Now, one question raises here, can we have two constructors as:

public class MyClass
{
Static MyClass ()
{
Initialization code goes here.
Can only access is static.
}
Public MyClass ()
{
Code for the "the" Myderivedclass constructor.
}

Other class methods goes
}
This is perfectly valid, the though doesn ' t seem to being in accordance with overloading. But Why? Because the time of the execution of the two methods are different. ' Is ' at the ' time of ' loading the ' assembly ' and ' is ' at the ' time ' of object creation.

Constructors FAQs
Is the constructor mandatory for a class?
Yes, it is mandatory to have the constructor of the class and that too should are accessible for the object i.e., it should Have a proper access modifier. Say, for example, we have only private constructor (s) in the class and if we are interested the class, I. E., want to create an object of class, then has only private constructor won't be sufficient and in fact it would Raise an error. So, proper access modifies should is provided to the constructors.

What if I do not write the constructor?
In such case, the compiler would try to supply the no parameter constructor for your class, behind the scene. Compiler'll attempt this is only if you don't write the constructor for the class. If you are provide any constructor (with or without parameters), then compiler won't make any such attempt.

What if I have the constructor public Myderivedclass (), but not the public mybaseclass ()?
It would raise an error. If either the no parameter constructor is absent or it are in-accessible (say it is private), it would raise an error. You'll have to take the precaution.

Can We access static members from the Non-static (normal) constructors?
Yes, we can. There is no such restriction on non-static constructors. But there is one on static constructors the It can access only the static members.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.