Pages

Monday, November 25, 2013

C#: Learn about Class, Object and Constructors

C#: Learn about Class, Object and Constructors

What is a class?Class is a blueprint of related variables, data types and methods. In very simple terms, a class is a definition for an object.Example
class Student{
public string Name {get;set;}
public string Age {get;set;}
}What is an object?Object is an instance for a class.
Student student = new Student();Generally, "new" keyword is used to create an instance.What is constructor?Constructor is a special method with name same as class name. It will be automatically when the new instance of class is created.Types of constructor
There are five different types of constructors available in C#.1) Default Constructor Or Silent Constructor
2) Parameterised Constructor
3) Private Constructor
4) Static Constructor
5) Copy ConstructorConstructor types explained

public Student(string Name)
{
Console.WriteLine("Parameterised Constructor is called");
this.Name = Name;
Console.WriteLine("Value of name is " + Name);
} public string Name {get;set; }
} Output:
Parameterised Constructor is calledValue of name is Muralidharan Deenathayalan3) Private Constructor When a constructor has a private access modifier then we can't create instance for that class. This type of constructor are used to restrict the class is being instantiated when it has all the methods as static methods.
using System.IO;
using System;
class Program
{
static void Main()
{
Student studentObject = Student.GetInstance();
}
}
public class Student
{
private Student()
{
Console.WriteLine("Private Constructor is called");
}

public static Student GetInstance()
{
if (Instance == null)
{
Instance = new Student();
}
return Instance;
} public static Student Instance {get;set; }
}Output:
Private Constructor is called 4) Static Constructor When a constructor is marked as static, it will be invoked only once for any number of instances of that class. It is also during the creation of the first reference to a static member in the class.
using System.IO;using System;
class Program
{
static void Main()
{
Student studentObject = new Student();
}
}
public class Student
{
public Student()
{
Console.WriteLine("Default Constructor is called");
}

5) Copy Constructor When a parameterised constructor has a parameter of same class type is called as copy constructor. This type of constructor is used to initialize new instance to the values of an existing instance
using System.IO;
using System;
class Program
{
static void Main()
{
//Parameterised Constructor will be called
Student studentObject1 = new Student("Muralidharan");