Constructors in C#

The syntax for declaring basic constructors in C# is the same as in Java and C++. We create a method that has the same name as the containing class, and which does not have any return type:
public class MyClass
{
   public MyClass()
   {
   }
}











As in C++ and Java, it’s not necessary to provide a constructor for your class. We haven’t supplied onefor any of our examples so far in the book. In general, if you don’t supply any constructor, the compilerwill just make up a default one for you behind the scenes. It’ll be a very basic constructor that just initializesall the member fields by zeroing them out (null reference for reference types, zero for numeric datatypes, and false for bools). Often, that will be adequate; if not, you’ll need to write your own constructor.

Constructors follow the same rules for overloading as other methods. In other words, you can provide as many overloads to the constructor as you want, provided they are clearly different in signature:

public MyClass() // zero-parameter constructor
{
  //construction code
}

public MyClass(int number)
{
  //construction code
}















Note, however, that if you supply any constructors that take parameters, then the compiler will not automatically supply a default one. This is only done if you have not defined any constructors at all. 
In the following example, because we have defined a one-parameter constructor, the compile assumes that this is the only constructor we want to be available, and so will not implicitly supply any others:


public class MyNumber
{
   private int number;
   public MyNumber(int number)
   {
      this.number = number;
   }
}














The previous code also illustrates typical use of the this keyword to distinguish member fields from parameters of the same name. If we now try instantiating a MyNumber object using a no-parameter constructor, we will get a compilation error:MyNumber number = new MyNumber(); // causes compilation error. We should mention that it is possible to define constructors as private or protected, so that they are invisible to code in unrelated classes too:


public class mNumber
{
   private int number;
   private mNumber(int number) // another overload
   {
      this.number = number;
   }
}














In this example we haven`t actually definde any public or even any protected constructors for mNumber.
This world actually make it impossible for mNumber to be instantiated by outside code using the new operator ( though you might write a public static property or method in mNumber that can instantiate the class). This is useful in two situations:
1.      If your class serves only as a container for some static members or properties, and therefore should never be instantiated

2.      If you want the class to only ever be instantiated by calling some static member function (this isthe so-called class factory approach to object instantiation) 
     

No comments:

Post a Comment