C# Constructor

Constructor is a function for object initialization. All classes has a default constructor base which will be called if there is not constructor provided.

Constructors are usually has the same name as the class and do not return values.

class human
{
public int age;
public human()
{ ... }
}

Constructor is usually public. If it is private, then no object can be created based on the class. The later usually happens when all class members are static.
class weekdays
{
private weekdays() {};
public static string[] arr = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
public static showweekday(int i)
{
i -= 1;
if (i < 0 && i > 6) return "NA";
return arr[i];
}
}
weekdays d = new weekdays(); //error
weekdays.showweekday(2); //Tuesday

A class may have multiple constructors with the same name but different parameters.
class human
{
public int age;
public string sex;
public string race;
public human()
{
sex = "unknown";
age = 0;
race = "unknown";
}
public human(int a,string s)
{
sex = s;
age = a;
race = "unknown";
}
public human(int a,string s,string r)
{
sex = s;
age = a;
race = r;
}
}
human h = new human(); //OK
h.age; //0
h.race; //unknown
human h2 = new human(28,"James"); //OK
h2.age; //28
h2.race; //unknown
human h3 = new human(28,"James","English"); //OK
h3.age; //28
h3.race; //English

Destructors are called when an object is destroyed for resouces release and other clearing tasks.
class human
{
public int age;
public human()
{ ... }
public ~human() //destructor
{ ... }
}



endmemo.com © 2017  Terms of Use | Home