Default constructor in C#

Posted on Updated on

Image result for C#Default constructor in C#

Whenever a constructor is not defined in a class, it is known as default constructor. Default constructor is basically without parameters. If no constructors are defined in a class, default constructor calls the parameter-less default constructor of the direct base class. If the direct base class does not have an accessible default constructor, the compiler throws error. By default the default constructors are public but if the class is abstract then the accessibility of the default constructor is protected.

Syntax:

public A() : base() {…….}

Or

protected A() : base() {………..}

[ in which ‘A’ is the class name ]

Example 1

class Message{

object sender;

string text;

}

a default constructor is provided because the class contains no instance constructor declarations. Thus, the example is precisely equivalent to

class Message

{

object sender;

string text;

public Message(): base() {}

}

Example 2

public class clsAddition{

publicintMycode = 0;

publicclsAddition(){

Mycode = 9;

         }

 }

class Program{

static void Main(string[] args){

clsAdditionobj = new clsAddition();

Consolw.WriteLine(“Code value is : {0}”,obj.Mycode);

  }

}

*****************************************************************************************************

For more details and queries please feel free to email, visit or call us. Wishing you the very best for all your future endeavors.
Helpline: 9814666333, 8699444666
Email: info@technocampus.co.in

Please fill the form and we shall contact you soon.

Leave a comment