Introduction:
Understanding constructors is very important for Object oriented designers and programmers.In this article,just i am trying to explain the concept of constructors and its uses.
Main:
Defn:
A constructor is a member function that has the same name as the class name and is invoked automatically when the class is instantiated. A constructor is used to provide initialization code that gets executed every time the class is instantiated.
1.Constructors should not be “virtual”.
2.Constructors should not be inherited.
3.If we don’t write any constructor for a class, C# provides an implicit default constructor, i.e., a constructor with no argument.
4.Constructors should not return any value.
5.Constructors can be overloaded.
[modifier_name] class_name (parameters)
{
// constructor body
}
Modifier_name can be,public,protected,internal,private,extern
Constructors can be calssified into the following two ways,
1.Static (class) constructors,
2.Non–static (instance) constructors
static constructors,
*cannot be overloaded.
*should be without parameters and can only access static members.
*should not have any access modifiers.
*no way to chained with other static or non-static constructors.
*static constructors will execute after instance constructor.(If we used both).
for ex,
class HELLO
{
static HELLO()
{
Console.Writeline("Hi,i am static constructor");
}
}
class HELLO { static HELLO() { Console.Writeline("Hi,i am static constructor"); } } |
Non–static constructors,
*can classified into parameterised,non-parameterised,
for ex,
class HELLO
{
public HELLO()
{
Console.Writeline("Hi,i am static constructor");
}
public HELLO(string WELCOMETEXT)
{
Console.Writeline("Hi,i am static constructor",+WELCOMETEXT);
}
}
class HELLO { public HELLO() { Console.Writeline("Hi,i am static constructor"); } public HELLO(string WELCOMETEXT) { Console.Writeline("Hi,i am static constructor",+WELCOMETEXT); } } |
Conclusion:
Hope this helps you to understand about constructors,
Happy Coding.
Hmmm…very good to find out, there were without a doubt a number of points that I had not thought of before.