Class is consists of data and behavior. Class data is represented by it's fields and behavior is represented by its methods.
Example:
class Customer
{
string first_Name;
string last_Name;
//Default parameterless constructor
public Customer() : this("No FirstName Provided", "No LastName Provided")
{
}
public Customer(string f_Name,string l_Name)
{
this.first_Name = f_Name;
this.last_Name = l_Name;
}
public void printFullName()
{
Console.WriteLine("Full Name = {0}" ,this.first_Name+" "+this.last_Name);
}
~Customer()//destructor call automatically
{
//Clean up code
}
}
class Program
{
static void Main(string[] args)
{
Customer C1 = new Customer("Brij","Pal"); //here constructor used to initializing the member of class
C1.printFullName();
Customer C2 = new Customer(); //Here called the default constructor
C2.printFullName();
Console.ReadLine();
}
}
Purpose of Constructors:
- The purpose of a class constructor is to initialize class fields. A class constructor is automatically called when an instance of class is created.
- Constructor do not have a return values and always have the same name as the class name.
- Constructors are not mandatory. if we do not provide a constructor, a default parameter less constructor is automatically provided.
- Constructors can be overloaded by the number and type of parameters.
Destructors:
- Destructors have the same name as the class with ~symbol in front of them.
- They don't take any parameters and do not return a value.
- Destructors are places where you could put code to release any resources your class was holding during lifetime.
- They are normally called when the C# garbage collector decides to clean your object from memory.
No comments:
Post a Comment