Thursday, January 31, 2008

Something about constructors

What is a constructor? Explain the New Keyword. What is a Private Constructor?
Constructor - A constructor is a function with the same name as that of the class. The Default Constructor of a class is without an argument. The default constructor ensures that every member data is initialized to a default value. Constructors provide a way for classes to initialize a state for their members. Note that constructors dont have a return type(not even void).
public SomeClass(){Console.Writeline("Vishal says, Default Constructor is called");}\public SomeClass(string str){Console.Writeline("Vishal says, Custom Constructor is called" + str);}
When a custom constructor is defined, the Default Constructor is not called. A constructor may also be overloaded.
New - This keyword may be used as a modifier and as an operator. When used as an operator, it creates an object on a heap to invoke constructors. When used an a modifier, it hides an inherited member from the base class member.
As an operator, it can be used to create an object and then to invoke the constructor of the class. See example below.
ExampleSomeClass objSomeClass = new SomeClass(); //Creating a class object and invoking its constructor
float amount = new float(); //Creating an object of the type, and invoking its constructor
As a modifier, it is used to explicitly hide a member from the base class. See example.
Examplepublic class MamaClass{public void SomeMethod() { ... }}
public class BabyClass : MamaClass{new public void SomeMethod() { .... }}
Private Constructor - When a constructor is created with a private specifier, it is not possible for other classes to derive from this class, neither is it possible to create an instance of this class. They are usually used in classes that contain static members only. It is also used to create Singleton classes.

No comments: