Monday 25 March 2013

Constructors in C Sharp


  • Constructors are the core concept of Object Oriented Language, So the compiler generates a default constructor with default field values at compile time, only if there is no custom constructor was created.
  • If the class or struct has a custom constructor , the compiler silently removes the default constructor.
  • When a class or struct is created , its constructor is called(Invoked when a class is instantiated and objects memory location is created).
  • Constructors can be overloaded and they don't return values so no return type is used including void.
  • we can call one constructor from another using 'this' keyword.
  • Car(int modelNumber) :  this() {  }
  • We can also use 'base' keyword if the class is inherited and wants the parent class constructor values to be loaded to child class.
  • Constructors should be public so that values will be assigned to current state(fields).
  • If private, we cannot instantiate the class(because the constructor will not be available or not accessible outside of that class.)
  • we can also create static constructor but only static fields can be assigned.
  • If struct , parameter constructors are not allowed.
  • It is legal to create custom constructor(struct type) with no parameters. As struct type is value type 'new' keyword to allocate memory object is optional.
  • Remember: Static constructors will be executed at random time but before the class is instantiated.

No comments:

Post a Comment