An Intro to Constructors in C#
来源:互联网 发布:仙界网络直播间笔趣阁 编辑:程序博客网 时间:2024/05/22 06:22
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:
Ang=cs>An class=cs-keyword>public An class=cs-keyword>class mySampleClass{ An class=cs-keyword>public mySampleClass() { An class=cs-comment>// This is the constructor method. } An class=cs-comment>// rest of the class members goes here.}
When the object of this class is instAntiated, this constructor will be executed. Something like this:
Ang=cs>mySampleClass obj =An class=cs-keyword>new mySampleClass() An class=cs-comment>// At this time the code in the constructor will // be executed
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:
Ang=cs>An class=cs-keyword>public An class=cs-keyword>class mySampleClass{ An class=cs-keyword>public mySampleClass() { An class=cs-comment>// This is the no parameter constructor method. An class=cs-comment>// First Constructor } An class=cs-keyword>public mySampleClass( An class=cs-keyword>int Age) { An class=cs-comment>// This is the constructor with one parameter. An class=cs-comment>// Second Constructor } An class=cs-keyword>public mySampleClass( An class=cs-keyword>int Age, An class=cs-keyword>string Name) { An class=cs-comment>// This is the constructor with two parameters. An class=cs-comment>// Third Constructor } An class=cs-comment>// 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:
Ang=cs>mySampleClass obj =An class=cs-keyword>new mySampleClass() An class=cs-comment>// At this time the code of no parameter An class=cs-comment>// constructor (First Constructor)will be executed mySampleClass obj = An class=cs-keyword>new mySampleClass( An class=cs-literal>12) An class=cs-comment>// At this time the code of one parameter An class=cs-comment>// constructor(Second Constructor)will be An class=cs-comment>// executed.
The call to the constructors is completely governed by the rules of overloading here.
Calling Constructor from Another Constructor
You cAn always make a call to one constructor from within Another. Say, for example:
Ang=cs>An class=cs-keyword>public An class=cs-keyword>class mySampleClass{ An class=cs-keyword>public mySampleClass(): An class=cs-keyword>this( An class=cs-literal>10) { An class=cs-comment>// This is the no parameter constructor method. An class=cs-comment>// First Constructor } An class=cs-keyword>public mySampleClass( An class=cs-keyword>int Age) { An class=cs-comment>// This is the constructor with one parameter. An class=cs-comment>// Second Constructor }}
Very first of all, let us see what is this syntax:
Ang=cs>An class=cs-keyword>public mySampleClass(): An class=cs-keyword>this( An class=cs-literal>10)
Here, Ang=cs>
refers to same class, so when we say Ang=cs>
, we actually meAn execute the Ang=cs>
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.e., which method will be executed when. Here, if I instAntiate the object as:
Ang=cs>mySampleClass obj =An class=cs-keyword>new mySampleClass()
Then the code of Ang=cs>
will be executed before the code of mySampleClass()
. So, practically the definition of the method:
Ang=cs>An class=cs-keyword>public mySampleClass(): An class=cs-keyword>this( An class=cs-literal>10){ An class=cs-comment>// This is the no parameter constructor method. An class=cs-comment>// First Constructor}
is equivalent to:
Ang=cs>An class=cs-keyword>public mySampleClass(){ mySampleClass( An class=cs-literal>10) An class=cs-comment>// This is the no parameter constructor method. An class=cs-comment>// First Constructor}
Note: Above (just above this line) code is mentioned there for pure Analogy And will not compile. The intention here is to tell the flow of execution if initializers are used.
We cAnnot make An explicit call to the constructors in C#, treating them as if Any simple method, for example: statement mySampleClass(
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 Ang=vbnet>
, but it should be the first line of 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 initializers here.
Note that only Ang=cs>
And Ang=cs>
(we will see it further) 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 proceed further.
Behavior of Constructors in inheritAnce
Let us first create the inherited class.
Ang=cs>An class=cs-keyword>public An class=cs-keyword>class myBaseClass{ An class=cs-keyword>public myBaseClass() { An class=cs-comment>// Code for First Base class Constructor } An class=cs-keyword>public myBaseClass( An class=cs-keyword>int Age) { An class=cs-comment>// Code for Second Base class Constructor } An class=cs-comment>// Other class members goes here} An class=cs-keyword>public An class=cs-keyword>class myDerivedClass : myBaseClass An class=cs-comment>// Note that I am inheriting the class here.{ An class=cs-keyword>public myDerivedClass() { An class=cs-comment>// Code for the First myDerivedClass Constructor. } An class=cs-keyword>public myDerivedClass( An class=cs-keyword>int Age): An class=cs-keyword>base(Age) { An class=cs-comment>// Code for the Second myDerivedClass Constructor. } An class=cs-comment>// Other class members goes here}
Now, what will be the execution sequence here:
If I create the object of the derived class as:
Ang=cs>myDerivedClass obj =An class=cs-keyword>new myDerivedClass()
Then the sequence of execution will be:
Ang=cs>
method.An class=cs-keyword>public myBaseClass() - And then
Ang=cs>
method.An class=cs-keyword>public myDerivedClass()
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 Ang=cs>
keyword, but it is still executing. This is the normal behavior of the constructor.
If I create An object of the derived class as:
Ang=cs>myDerivedClass obj =An class=cs-keyword>new myDerivedClass( An class=cs-literal>15)
Then the sequence of execution will be:
Ang=cs>
methodAn class=cs-keyword>public myBaseClass( An class=cs-keyword>int Age) - And then
Ang=cs>
methodAn class=cs-keyword>public myDerivedClass( An class=cs-keyword>int Age)
Here, the new keyword Ang=cs>
has come into picture. This refers to the base class of the current class. So, here it refers to the myBaseClass
. And Ang=cs>
refers to the call to Ang=cs>myBaseClass(
method.
Also note the usage of Age
variable in the syntax: Ang=cs>
. [UnderstAnding it is left to the reader].
Private Constructors
Private constructors, the constructors with the “Ang=cs>
” 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 Ang=cs>
constructors. But yes, we cAn have the set of Ang=cs>
constructors along with the Ang=cs>
constructors in the class And the Ang=cs>
constructors cAn access the Ang=cs>
constructors from within the class through constructor chaining.
Say for example, my class is something like this :
Ang=cs>An class=cs-keyword>public An class=cs-keyword>class myClass{ An class=cs-keyword>private MyClass() { Console.WriteLine( An class=cpp-string>"This is no parameter Constructor"); } An class=cs-keyword>public MyClass( An class=cs-keyword>int var): An class=cs-keyword>this() { Console.WriteLine( An class=cpp-string>"This is one parameter Constructor"); } An class=cs-comment>// Other class methods goes here}
Then we cAn create the object of this class by the statement:
Ang=cs>MyClass obj =An class=cs-keyword>new MyClass( An class=cs-literal>10);
The above statement will work fine, but the statement
Ang=cs>MyClass obj =An class=cs-keyword>new MyClass();
will raise An error : Ang=cs>'Constructors.MyClass.MyClass()'
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 constructor 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 they? Let us see..
Static Constructors
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 cAnnot 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:
Ang=cs>An class=cs-keyword>public An class=cs-keyword>class myClass{ An class=cs-keyword>static myClass() { An class=cs-comment>// initialization code goes here. An class=cs-comment>// CAn only access static members here. } An class=cs-comment>// Other class methods goes here}
Notes for Static Constructors:
- 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 like that? Let us go step by step here.
Firstly, the call to the static method is made by the CLR And not by the object, so we do not need to have the access modifier to it.
Secondly, it is going to be called by CLR, who cAn pass the parameters to it, if required. So we cAnnot have parameterized static constructor.
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.
Fourthly, overloading needs the two methods to be different in terms of methods definition, which you cAnnot do with Static Constructors, so you cAn have at the most one static constructor in the class.
Now, one question raises here, cAn we have two constructors as:
Ang=cs>An class=cs-keyword>public An class=cs-keyword>class myClass{ An class=cs-keyword>static myClass() { An class=cs-comment>// initialization code goes here. An class=cs-comment>// CAn only access static members here. } An class=cs-keyword>public myClass() { An class=cs-comment>// Code for the First myDerivedClass Constructor. } An class=cs-comment>// Other class methods goes here}
This is perfectly valid, though doesn’t 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
- Is the constructor mAndatory for a class?
Yes, it is mAndatory to have the constructor in the class And that too should be 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 in instAntiating the class, i.e., wAnt to create An object of the class, then having only private constructor will not be sufficient And in fact it will raise An error. So, proper access modifies should be provided to the constructors.
- What if I do not write the constructor?
in such case, the compiler will try to supply the no parameter constructor for your class, behind the scene. Compiler will attempt this only if you do not write the constructor for the class. If you provide Any constructor (with or without parameters), then compiler will not make Any such attempt.
- What if I have the constructor
Ang=cs>
, but not theAn class=cs-keyword>public myDerivedClass() Ang=cs>
?An class=cs-keyword>public myBaseClass() It will raise An error. If either the no parameter constructor is absent or it is in-accessible (say it is
Ang=cs>
), it will raise An error. You will have to take the precaution here.An class=cs-keyword>private - 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 that it cAn access only static members.
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
- An Intro to Constructors in C#
- An Intro to Constructors in C#
- An Intro to Constructors in C#
- An Introduction to Business Objects in C#
- An Introduction to Reflection in C#
- An intro to map from mapschool
- An intro to modern OpenGL. Chapter 1: The Graphics Pipelinehttp://duriansoftware.com/joe/An-intro-to
- Serialization from an Object to XML Document in C#
- An introduction to Z-Wave programming in C#
- Mocking a method to throw an exception in C#
- Introduction to Constructors and Destructors in VB.NET
- An intro to modern OpenGL. Chapter 2.1: Buffers and Textures
- An intro to modern OpenGL. Chapter 2.2: Shaders
- An intro to modern OpenGL. Chapter 2.3: Rendering
- Assembly Intro - An Introduction to the SSE Instruction Set
- Constructors in C++11
- How To Use a DataReader Against an Oracle Stored Procedure in Visual C# .NET
- Different ways how to escape an XML string in C# (zz)
- MapX 控件在C# 中的应用 (一)
- 学习--“Edit控件”
- 在你的服务器端代码中使用线程和创建异步处理(4)
- 转:2008年最值得期待的八大垂直搜索引擎
- 巧用头脑思考,提高软件运行效率-浅谈程序算法
- An Intro to Constructors in C#
- .NET – 深入系统编程 - Part 1
- 学习二--“Listctrl控件”
- 将 ASP.NET 输出缓存与 SQL Server 结合使用
- 在你的服务器端代码中使用线程和创建异步处理(结束)
- 被判3年罚250万 珊瑚虫QQ作者提起上诉
- 奋斗好了虚拟机、成功安装好RH AS5
- 使用C#拷贝String到struct
- 在ADO.NET中使用事务保护数据的完整性(1)