Eleventh Class (constructor and Destructor)
constructor and destructor in c sharpconstructor :
1. Same name as class name.
2. Constructor call automatically in Main().
3. No return type use to declare constructor.
Example of constructor
using System;
{
car()
{
Console.WriteLine("Constructor Invoked");
}
public static void Main()
{
car c=new car();
}
}
Here car() is constructor and dont need to access it through object.
Two type of Constructor
1. Instance constructor
2. Static constructor
1. Instance Constructor
Instance variable is use to instance data member of a class.
N number of constructor can be declare in a class.
Example of Instance Constructor
using System;
class car
{
int a, b, c;
{
a=2;b=3;
c=a+b;
Console.WriteLine("Result is :"+c);
}
public static void Main()
{
car c = new car();
}
}
Example 2
using System;
class car
{
int a, b, c;
car()
a=2;b=3;
c=a+b;
Console.WriteLine("Result is :"+c);
}
public void color()
{
Console.WriteLine("hi this is red color");
}
public static void Main()
{
car c = new car();
c.color();
}
}
2. static constructor
static constructor is use to initialize the static variable of a class.
using System;
{
cons()
{
Console.WriteLine("this is first constructor");
}
static cons() //static constructor run at first...
{
Console.WriteLine("this is second constructor");
}
public static void Main()
{
cons c=new cons();
}
}
No comments:
Post a Comment