An Intro to Constructionors in C #

zhaozj2021-02-16  53

This is an article on Constructors in C #, for the beginner level programmers. It covers simple constructors, constructors overloading, behaviour of constructors in inheritance, constructor chaining and 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 its object is created Usually, we put the initialization code in the constructor Writing a constructor in the class is 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 Object of this class is instantiated, this constructor will be executed. Something Like this:

MySampleClass Obj = new mysampleclass ()

// at this time the code in the constructor will // be per eluted

Constructor overloading

C # Supports Overloading of Constructors, That Means, We Can Have Constructors with Different Sets of Parameters. So, Our Class Can Be Like this:

Public class mysampleclass

{

Public mysampleclass ()

{

// this is the no parameter constructor method.

// first Constructor

}

Public MySampleClass (Int Age)

{

// this is the constructor with one parameter.

// Second Constructionor

}

Public MySampleClass (int Age, String Name)

{

// this is the constructor with two parameters.

// Third Constructionor

}

// REST OF THE CLASS MEMBERS GoES HERE.

}

Well, Note Here That Call to The Constructor Now Depends on the Way you instantiate the object. For example:

MySampleClass Obj = new mysampleclass ()

// at this time the code of no parameter

// Constructor (First Constructor) Will Be Execute

MySampleClass Obj = new mysampleclass (12) // at this time the code of one parameter

// Constructor (Second Construction) Will B

// executed.

The call to the constructors is completely governed by the rules of overloading here.

Calling Constructionor from another constructor

You can always make a call to one constructor from Withnother. Say, for Example:

Public class mysampleclass

{

Public mysample (): this (10)

{

// this is the no parameter constructor method.

// first Constructor

}

Public MySampleClass (Int Age)

{

// this is the constructor with one parameter.

// Second Constructionor

}

}

Very First of All, Let us See What this Syntax:

Public mysample (): this (10)

Here, this refers to same class, so when we say this (10), we actually mean execute the public mySampleClass (int Age) method. The above way of calling the method is called initializer. We can have at the most one initializer in THIS WAY IN The Method.

Another Thing Which WE Must Know Is The Execution Sequence I., Which Method Will Be Executed When. Here, IF I Instantiate The Object As:

MySampleClass Obj = new mysampleclass ()

THE CODE OF PUBLIC MYSAMPLECLASS (INT Age) Will Be Executed Before The Code of MySample Class (). So, Practically The Definition of the Method:

Public mysample (): this (10)

{

// this is the no parameter constructor method.

// first Constructor

}

IS Equivalent TO:

Public mysampleclass ()

{

MySampleClass (10)

// this is the no parameter constructor method.

// first Constructor

}

Note: Above (Just Above This Line) Code Is Mentioned There for Pure Analogy and Will Not Compile. The intendion here is to tell the flow of executioniffness.

We can not make an explicit call to the constructors in C #, treating them as if any simple method, for example:. Statement mySampleClass (10) in the above code will not work The only way you can call one constructor from another is through initializers. For the VB.NET programmers: you can make the call to another constructor of the same class by the syntax Me.New (param list), but it should be the first line of your calling constructor method So ultimately, the code of the. .

Note That Only This and Base (We will see it it it) Keywords are allowed in Initializers, Other Method Calls Will Raise An Error.

This Is Sometimes Called Constructor Chaining.

HUFF ... Simple Thing Made Tough, But this is how it is. Anyway, let us proced further.

Behavior of Constructors in inheritance

Let us first create the inherited class.

Public class mybaseclass

{

Public mybaseclass ()

{

// Code for First Base Class Constructor

}

Public mybaseclass (int Age)

{

// Code for Second Base Class Constructor

}

// other class memory goes here

}

Public class myderivedclass: mybaseclass

// Note That I am inheriting the class here.

{

Public myderivedclass ()

{

// Code for the first myderivedclass constructor.

}

Public MyderiveDclass (int Age): Base (agn)

{

// code for the second myderivedclass constructor.

}

// other class memory goes here

}

Now, What Will Be The Execution Sequence HERE:

If i create the object of the derived class as:

MyderivedClass Obj = new myderivedclass ()

THE SEQUENCE OF EXECUTION WILL BE:

Public mybaseclass () method () method () Method.

Note: If we do not provide initializer referring to the base class constructor then it executes the no parameter constructor of the base class.Note one thing here: we are not making any explicit call to the constructor of base class neither by initializer nor by the 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)

THE SEQUENCE OF EXECUTION WILL BE:

Public mybaseclass (int Age) method and then public myderivedclass (int Age) Method

Here, The New Keyword Base Has Come Into Picture. This Refers To The Base Class of The Current Class. So, Here It Refers To The MyBaseClass. And Base (10) Refers to the call to mybaseclass (int Age) Method.

Also Note The Usage of Age Variable in The 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 the class, nor can we inherit the class with only private constructors. But yes, we can have the Set of public constructors involtructors in the class and the public constructors......................... ...CRIPLILE, TELILS.

Say for Example, My Class Is 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);

}

// taher class methods goes here

}

Then we can create the object of this class by the state:

Myclass obj = new myclass (10);

The Above Statement Will Work Fine, But The Statement

Myclass obj = new myclass ();

Will Raise An Error: 'Constructors.myclass.Myclass ()' Is Inaccessible Due To ITs 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 be inherited. If we try to inherit the class with only private constructors then we will get the same error as above. Also Recall, ONCE You Provide Constructor from your Side The Compiler Will NOT Add The No-Parameter Public Construction To your class.

Well, One of the Usage Scenarios Of Such Class Could Be - When You Have Only Static Members in The Class and You Don't need to instantiate it.

PHEW ... LOST ... Anything Left in Constructors? Yes, Static Constructors. Ha !! now, what are the. Let us See ..

Static Constructionors

This is a new concept introduced in C #. By new here, I mean that it was not available for the C developers. This is a special constructor and gets called before the first object is created of the class. The time of execution can not be determined , But it is definitely before the first object creation - could be at the time of 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 Static MEMBERS Here.

}

// taher class methods goes here

}

Notes for Static Constructionors:

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

Firstly, The call to the static method is due by the clr and not by the object, so we do not need to it.

Secondly, IT is Going to Be Called By Cl R, WHO CAN Pass The Parameters to It, IF Required. So We Cannot Have Parameterized Static Construction.

Thirdly, non-static members in the class are specific to the object instance. So static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only Static MEMBERS OF 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 Static MEMBERS Here.

}

Public myclass ()

{

// Code for the first myderivedclass constructor.

}

// taher class methods goes here

}

This is perfectly valid, though does not seem to be in accordance with overloading concepts. But why? Because the time of execution of the two methods are different. One is at the time of loading the assembly and one is at the time of object CREATION.

Constructors FAQS

转载请注明原文地址:https://www.9cbs.com/read-23054.html

New Post(0)