Saturday, February 23, 2013

C# Constructors



1. Constructor is special method of a class that has the same name as the class and that does not have any return value.
2. A constructor that does not take any parameter (i.e. parameter less) is called default constructor.
3. In C#, all classes (except static classes) and structs are required to have default (parameter less) constructor.
4. static classes are not required to have default constructor. But if a constructor is provided to static class, then it must be static and it must be parameter less.
              *static classes cannot have instance constructors.
              *static class constructor must be static
              *static class constructor must be parameter less.
In short static classes can have only one constructor, and it must be static and parameter less.
5. structs  CANNOT have explicit default constructor. A default constructor is always provided by compiler to structs and it not allowed to code default constructor for structs.
6. Classes can have multiple constructors, each with different signature. These are called overloaded constructors.
7. If a parametered constructor is provided for a class, then default constructor MUST also be provided. Compiler provides default constructor only when no constructors are provided to the class.
8. Abstract classes can also have constructors, and rules for abstract class constructors are same as those of any non-static class constructors.

No comments:

Post a Comment