Easy Tutorial
❮ Csharp Windows File System Csharp Nested Switch ❯

C# Class

When you define a class, you are defining a blueprint for a data type. This does not actually define any data, but it defines what the class name means, that is, what an object of the class consists of and what operations can be performed on this object. An object is an instance of a class. The methods and variables that constitute a class are called members of the class.

Class Definition

A class definition starts with the keyword class, followed by the class name. The class body, which includes a pair of curly braces. Below is the general form of a class definition:

<access specifier> class class_name 
{
    // member variables
    <access specifier> <data type> variable1;
    <access specifier> <data type> variable2;
    ...
    <access specifier> <data type> variableN;
    // member methods
    <access specifier> <return type> method1(parameter_list) 
    {
        // method body 
    }
    <access specifier> <return type> method2(parameter_list) 
    {
        // method body 
    }
    ...
    <access specifier> <return type> methodN(parameter_list) 
    {
        // method body 
    }
}

Please note:

The following example illustrates the concepts discussed so far:

Example

using System;
namespace BoxApplication
{
    class Box
    {
       public double length;   // Length
       public double breadth;  // Breadth
       public double height;   // Height
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();        // Declare Box1, of type Box
            Box Box2 = new Box();        // Declare Box2, of type Box
            double volume = 0.0;         // Volume

            // Box1 specification
            Box1.height = 5.0;
            Box1.length = 6.0;
            Box1.breadth = 7.0;

            // Box2 specification
            Box2.height = 10.0;
            Box2.length = 12.0;
            Box2.breadth = 13.0;

            // Volume of Box1
            volume = Box1.height * Box1.length * Box1.breadth;
            Console.WriteLine("Volume of Box1: {0}", volume);

            // Volume of Box2
            volume = Box2.height * Box2.length * Box2.breadth;
            Console.WriteLine("Volume of Box2: {0}", volume);
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following result:

Volume of Box1: 210
Volume of Box2: 1560

Member Functions and Encapsulation

Class member functions are functions that have their definition or prototype within the class definition, just like other variables. As members of the class, they can operate on any object of the class and can access all members of that object's class.

Member variables are the attributes of an object (from a design perspective) and they are kept private to achieve encapsulation. These variables can only be accessed using public member functions.

Let's use the above concepts to set and get the values of different class members in a class:

Example

using System;
namespace BoxApplication
{
    class Box
    {
       private double length;   // Length
       private double breadth;  // Width
       private double height;   // Height
       public void setLength( double len )
       {
           length = len;
       }

       public void setBreadth( double bre )
       {
           breadth = bre;
       }

       public void setHeight( double hei )
       {
           height = hei;
       }
       public double getVolume()
       {
          return length * breadth * height;
       }
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();        // Declare Box1, of type Box
            Box Box2 = new Box();        // Declare Box2, of type Box
            double volume;               // Volume


            // Detailed description of Box1
            Box1.setLength(6.0);
            Box1.setBreadth(7.0);
            Box1.setHeight(5.0);

            // Detailed description of Box2
            Box2.setLength(12.0);
            Box2.setBreadth(13.0);
            Box2.setHeight(10.0);

            // Volume of Box1
            volume = Box1.getVolume();
            Console.WriteLine("Volume of Box1: {0}", volume);

            // Volume of Box2
            volume = Box2.getVolume();
            Console.WriteLine("Volume of Box2: {0}", volume);

            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following result:

Volume of Box1: 210
Volume of Box2: 1560

Constructors in C

A constructor of a class is a special member function that is executed when a new object of the class is created.

The constructor has the same name as the class and does not have any return type.

The following example illustrates the concept of constructors:

Example

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of the line
      public Line()
      {
        Console.WriteLine("Object is created");
      }

      public void setLength( double len )
      {
        length = len;
      }
      public double getLength()
      {
        return length;
      }

      static void Main(string[] args)
      {
        Line line = new Line();    
// Set line length
line.setLength(6.0);
Console.WriteLine("Line length: {0}", line.getLength());
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:

Object created
Line length: 6

Default Constructor does not have any parameters. However, if you need a constructor with parameters, you can have one, which is called a parameterized constructor. This technique helps you to assign initial values to an object at the time of creation, as shown in the following example:

Example

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Line length
      public Line(double len)  // Parameterized constructor
      {
         Console.WriteLine("Object created, length = {0}", len);
         length = len;
      }

      public void setLength(double len)
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line(10.0);
         Console.WriteLine("Line length: {0}", line.getLength()); 
         // Set line length
         line.setLength(6.0);
         Console.WriteLine("Line length: {0}", line.getLength()); 
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following result:

Object created, length = 10
Line length: 10
Line length: 6

Destructor in C

A destructor in a class is a special member function that is executed when the object of the class goes out of scope.

The name of the destructor is the class name prefixed with a tilde (~), it does not return a value and it does not take any parameters.

Destructors are used to release resources before exiting the program, such as closing files, freeing memory, etc. Destructors cannot be inherited or overloaded.

The following example illustrates the concept of a destructor:

Example

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Line length
      public Line()  // Constructor
      {
         Console.WriteLine("Object created");
      }
      ~Line() // Destructor
      {
         Console.WriteLine("Object deleted");
      }

      public void setLength(double len)
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();
         // Set line length
         line.setLength(6.0);
         Console.WriteLine("Line length: {0}", line.getLength());         
      }
   }
}

When the above code is compiled and executed, it produces the following result:

Object created
Line length: 6
Object deleted

Static Members of a C# Class

We can use the static keyword to declare a class member as static. When a class member is declared as static, it means that no matter how many objects of the class are created, there is only one copy of the static member.

The keyword **static** means there is only one instance of the member in the class. Static variables are used to define constants, as their values can be obtained by directly calling the class without creating an instance of the class. Static variables can be initialized outside the member function or the class definition. You can also initialize static variables inside the class definition.

The following example demonstrates the usage of **static variables**:

## Example

using System; namespace StaticVarApplication { class StaticVar { public static int num; public void count() { num++; } public int getNum() { return num; } } class StaticTester { static void Main(string[] args) { StaticVar s1 = new StaticVar(); StaticVar s2 = new StaticVar(); s1.count(); s1.count(); s1.count(); s2.count(); s2.count(); s2.count();
Console.WriteLine("Variable num for s1: {0}", s1.getNum()); Console.WriteLine("Variable num for s2: {0}", s2.getNum()); Console.ReadKey(); } } }


When the above code is compiled and executed, it produces the following result:

Variable num for s1: 6 Variable num for s2: 6


You can also declare a **member function** as **static**. Such functions can only access static variables. Static functions exist before an object is created. The following example demonstrates the usage of **static functions**:

## Example

using System; namespace StaticVarApplication { class StaticVar { public static int num; public void count() { num++; } public static int getNum() { return num; } } class StaticTester { static void Main(string[] args) { StaticVar s = new StaticVar(); s.count(); s.count(); s.count();
Console.WriteLine("Variable num: {0}", StaticVar.getNum()); Console.ReadKey(); } } }


When the above code is compiled and executed, it produces the following result:

Variable num: 3 ```

❮ Csharp Windows File System Csharp Nested Switch ❯