Flipkart Search

Search This Blog

Wednesday, March 18, 2009

Classes in C#

A class is a datastructure that may contain
  • Data Members
    • Constants
    • Fields
  • Function Members
    • Methods
    • Properties
    • Events
    • Indexers
    • Operators
    • Instance constructors
    • Static Constructors
    • Destructors
An example of how you can declare a class is shown below.We will discuss about Access Modifiers, Attributes and Class-Modifiers in our later article. Access Modifiers, Attributes and Class-Modifiers are optional in a class declaration.

[Attributes] [Access Modifiers] [Class-Modifiers] class Class-Name
{
//Body of the class
}

In the example below
  • We have a class with name ClassDemo. In this class we have 2 fields, 1 constructor and a method.
  • Out of the 2 fields we have, One field is a constant and the other is a variable of type integer. Fields are generally used to store the data related to the class.
  • The difference between variables and constants is that you can declare a variable at one place, assign a value to it at another place and you can also change the value later in the code. Where as for a constant you can only assign a value when you declare it. This is a common interview question generally asked.
  • The constructor of this class is used to initialize the private data field _radius. Construtors are generally used to initialize the class datafields. Constructors will have the same name as that of a class and does not have return type. This is how we can differentiate a constructor from a method.
  • Finally we have a method CalculateArea() which calculates the area of the circle. For clear understanding of what are methods, Difference between static and instance methods and Different types of method parameters read Methods in C# article.
  • In the Main method we create an instance of ClassDemo using the new operator. When an Instance of class is created the constructor is automatically called. In our example ClassDemo constructor is called passing it a value of 10. The constructor then uses this value to initialize the private data field _radius.

using System;

public class ClassDemo

{

//Data Members for the class

const double PI = 3.14; // Constant field Declaration

private int _radius; // Privta field Declaration

//Instance Constructor Declaration with one parameter

public ClassDemo(int Radius)

{

Console.WriteLine("Constructor Called");

this._radius = Radius;

//The line below will generate a compile time error

//PI = 486;

}

//Instance Method Declaration

public double CalculateArea()

{

//Calculate the area of circle

return (PI * _radius * _radius);

}

}

public class MainClass

{

public static void Main()

{

//Create an instance of the class with new operator

ClassDemo CD = new ClassDemo(10);

Console.WriteLine("Area of the Circle is : " + CD.CalculateArea());

}

}

All about Constructors in a class in C#
There are 4 different types of constructors in a class as listed below
  1. Default Parameter less constructor
  2. Private constructor
  3. Static constructor
  4. Instance constructor
  • Default Parameter less constructor: If we donot have any constructor in a class, .NET provides a default parameter less constructor. This constructor will automatically initialize the class data fields to their default values. In our example as we donot hava an explicit constructor defined, a default parameter less constructor will be provided which will initialize the _Name field to empty string and _Age field to 0. In the example below, we have two properties Name and Age defined for the private data fields _Name and _Age respectively. For a clear understanding of what are properties, why they are used, abstract properties and Interface properties read Properties in C#

    using System;

    public class DefaultConstructorDemo

    {

    private string _Name;

    private int _Age;

    public string Name

    {

    get

    {

    return _Name;

    }

    }

    public int Age

    {

    get

    {

    return _Age;

    }

    }

    }

    public class MainClass

    {

    public static void Main()

    {

    DefaultConstructorDemo DCD = new DefaultConstructorDemo();

    Console.WriteLine("Name = " + DCD.Name + " Age = " + DCD.Age);

    }

    }

  • Private Constructor :
    1. Priavte constructors are created using the private access modifier. Any method, property, constructor or a datafield that has a private access modifier can be accessed only with in the class. We will discuss about access modifiers in our later article.
    2. One common interview question is, How do you prevent a class from being instantiated? The answer is using priavte constructors. As PrivateConstructorDemo() constructor has a private access modifer we cannot create an instance of PrivateConstructorDemo class in MainClass.
    3. Any time we define an explicit constructor to our class, the default parameter less constructor will not be provided by .NET
    4. If a class has only static and constant datafields whose value will not change on a per object basis, it does not make any sense to create multiple instances of that class. So in this case we want to prevent users from creating instances of the class, which can be achieved using a private constructor as shown in the below example.
    5. It is a compile time error to instantiate a class that has a private constructor.

    using System;

    public class PrivateConstructorDemo

    {

    //Private Constructor prevent object instantiation

    private PrivateConstructorDemo()

    {

    }

    public const double PI = 3.14;

    }

    public class MainClass

    {

    public static void Main()

    {

    //Line below will generate a compile time error.

    //PrivateConstructorDemo PV = new PrivateConstructorDemo();

    Console.WriteLine(PrivateConstructorDemo.PI);

    }

    }

  • Static constructor :
    1. Static Constructors are created by prefixing the static keword before the constructor as shown in the below example.
    2. Static Constructors are used to instantiate static data fields in the class. Static Constructors are called only once no matter how many instances you create for that class.
    3. Static Constructors are executed before any other type of constructor. Static Constructors cannot be called explicitly. They are automatically invoked when
      1. An instance of the class is created
      2. Any of the static members of the class are referenced
    4. It is a compile time error to have access modifiers for static constructors.

    using System;

    public class StaticConstructorDemo

    {

    public static int InterestRate;

    //Static Constructor

    static StaticConstructorDemo()

    {

    InterestRate = 10;

    }

    }

    public class MainClass

    {

    public static void Main()

    {

    //Static Constructor is automatically called as we

    //are referencing the static field of the class.

    Console.WriteLine(StaticConstructorDemo.InterestRate);

    }

    }

  • Instance Constructor :
    1. Instance Constructors are used to initialize the object data fields.
    2. It is possible to have multiple instance constructors for a class depending on the number of parameters passed to the constructor as shown below. This is called constructor overloading.
    3. A common interview question: What is constructor overloading. Having multiple instance constructors in a class with the same name but different number of parameters.

    using System;

    public class InstanceConstructorDemo

    {

    public int x, y;

    //Instance Constructor 1

    public InstanceConstructorDemo()

    {

    x = 0;

    y = 0;

    }

    //Instance Constructor 2

    public InstanceConstructorDemo(int x)

    {

    this.x = x;

    this.y = 0;

    }

    //Instance Constructor 3

    public InstanceConstructorDemo(int x,int y)

    {

    this.x = x;

    this.y = y;

    }

    }

    public class MainClass

    {

    public static void Main()

    {

    //Create instance using Instance Constructor 1

    InstanceConstructorDemo ICD1 = new InstanceConstructorDemo();

    Console.WriteLine("x = {0},y = {1}", ICD1.x, ICD1.y);

    //Create instance using Instance Constructor 2

    InstanceConstructorDemo ICD2 = new InstanceConstructorDemo(10);

    Console.WriteLine("x = {0},y = {1}", ICD2.x, ICD2.y);

    //Create instance using Instance Constructor 3

    InstanceConstructorDemo ICD3 = new InstanceConstructorDemo(100,200);

    Console.WriteLine("x = {0},y = {1}", ICD3.x, ICD3.y);

    }

    }
Destructors in C#
  1. A destructor will have the same name of a class prefixed by a tilde (~) symbol and cannot have parameters and return type. As destructors cannot have parameters it is not possible to overload destructors of a class. A class can have, at most, one destructor
  2. A destructor is a class member that implements the actions required to destruct an instance of a class.
  3. Destructors are invoked automatically, and cannot be invoked explicitly. Destructors are called automatically when the garbage collector runs. We will discuss about garbage collector in our later article.
  4. It is a compile time error to have access modifiers on destructors.

    using System;

    public class DestructorDemo

    {

    ~DestructorDemo()

    {

    Console.WriteLine("Destructor called");

    }

    }

    public class MainClass

    {

    public static void Main()

    {

    DestructorDemo DD = new DestructorDemo();

    DD = null;

    GC.Collect();

    }

    }

No comments: