C# - Class and Objects

    1 Votes


A class enables us to create our own custom types by grouping variables together of different types, methods and events. A class is just like a blueprint, which defines the data and behaviour of a type. If the class is not declared static then the code can used by creating objects or instances which are assigned to a variable.

The variable remains in the memory till all the references go out of scope and at that time the CLR will mark it eligible for garbage collection. But if the class is declared static then there can be only copy of it in the memory and the code can access it through class itself not through an object.

The classes support inheritance which is a fundamental characteristic of an object oriented programming. The syntax for a class is

class  class_name
{
   // member variables
     variable1;
     variable2;
   .
   .
     variableN;
   // member methods
     method1 (parameter_list)
   {
      // method body
   }
     method2 (parameter_list)
   {
      // method body
   }
   .
   .
     method n (parameter_list)
   {
      // method body
   }
}

Let us understand classes through an example:

using System;
namespace ConsoleApplication1
{
    class Square
    {
       public int a;   
    }
    class square
    {
        static void Main (string[] args)
        {
            Square sq = new Square ( ); 
            int area = 0;  
            sq.a = 5;        
            area = sq.a * sq.a;
           Console.WriteLine ("The area of square is: {0}",  area);
           Console.ReadKey ();
        }
    }
}

Output: The area of square is: 25

Objects

The class and an object both are different things. The class defines a type of object but it is not an object itself. The object is an entity based on a class and is referred as instance of a class. They can be created using new keyword which is followed by the name of the class that the object will be based on, like:

Square sq = new Square ();

When the instance of the class is created a reference of that object is passed back, in the above example sq is a reference to an object which is based on Square. We can also create object reference without creating an object, like this:

Square sq;

In this we are trying to access an object through such a reference which will cause error at run time, so we do not recommend creating object reference like this one which does not refer to an object. Instead of this we can refer such an object by either by creating a new object or by assigning it to existing object, like this:

Square sq = new Square ();
Square sq1 = sq;

In this we have created two object references which refer to the same object. If we try to make any changes in sq object then it will be reflected in the sq1 object because objects which are based on classes are referred by reference and they are known as reference types.

Access Specifiers

Every data type and type members have an accessibility level, which controls whether they can be used from other code in your assembly or other assemblies. Some of the access specifiers are:

  • Public: The public keyword is an access modifier for the data type and type members. Public access is the most liberal access level. There are no restrictions on accessing public members.
  • Private: The private keyword is a member access modifier. Private access has the least liberal access level. Private members can be access only within the body of the class or the struct in which they are declared. Nested types in the same body can also access the private members. 
  • Protected: The protected keyword is a member access modifier. A protected member can be access within its class and by derived class instances. Struct members cannot be protected because the struct cannot be inherited.
  • Internal: The internal keyword is an access modifier for types and type members. Internal types or members can be access only within files in the same assembly. It is used in component based programming
  • Protected internal: The types or members which are declared with protected internal can be accessed from the current assembly or from the types which are derived from the base class.

Member Functions

The member function of a class is a function which has its definition or prototype within the class definition which is similar to any other variable. It can operate on any object of the class of which it is a member, and can access all the members of a class for that object.

The member variables are the attributes of an object and they are kept private to implement encapsulation. These variables can be only accessed by using the public member functions. Let us have an example:

using System;
using System;
namespace ConsoleApplication
{
   class Square
   {
      private int side;   
      public void setSide( int s )
      {
         side = s;
      }
        public int getArea()
      {
         return side * side;
      }
   }
   class square
   {
      static void Main(string[] args)
      {
         Square sq = new Square();   
         int area;         
         sq.setSide(5);
        // area of square
         area = sq.getArea();
         Console.WriteLine ("The area is: {0}", area);
         Console.ReadKey ( );
      }
   }
}

Output: The area is: 25

Constructors

The class constructor is a special member function of a class that will be executed when the new objects of that class is created. A constructor has the same name as that of the class and it does not have any return type. It allows the programmer to set default values, limit instantiation, and write the code that is flexible and easy to read.

If we are not declaring constructor, C# will create public constructor by default which instantiates the object and sets the member variables to the default values. A class can have multiple constructors which take different arguments. A constructor that does not have parameters is called a default constructor. Default constructors are invoked when the object is instantiated by using the new operator and no arguments are provided to new.

Static classes and structs can also have constructors and that too parameter constructors which are known as Parameterized Constructor. Constructors can be public, private, protected, and internal or protected internal. Constructor can even be declared as static also. Let us have an example:

using System;
namespace ConsoleApplication1
{
   class Square
   {
      private int side;   
      public Square()
      {
         Console.WriteLine ("The object is created");
      }
      public void setSide( int s )
      {
         side = s;
      }
      public int getSide()
      {
         return side;
      }
      static void Main(string[] args)
      {
        Square sq = new Square();      
         sq.setSide(5);
         Console.WriteLine ("The area is: {0}", sq.getSide( ));
         Console.ReadKey ( );
      }
   }
}

Output: The object is created
The area is: 5

Destructors

The destructor is a special member function of a class that will be executed when the object of its class goes out of scope. It has exactly the same name as that of the class with a prefixed tilde sign (~) and it can neither return a value nor can take any parameters.

They are useful for releasing memory resources before exiting the program. They cannot be inherited or overloaded. They are used to destruct instances of classes. They cannot be defined in structs. They are only used with classes. A class can only have one destructor. They cannot be inherited or overloaded. Destructors cannot be called but they are invoked automatically. For example:

class Emp { ~Emp() // destructor { // cleanup statements... } }

The destructor implicitly calls Finalize on the base class of the object. The programmer cannot control the destructor when it is called because this is determined by the garbage collector. The garbage collector checks for those objects which are no longer in use by the application.

If it is considered as an object eligible for destruction, it calls the destructor and reallocates the memory which was used to store the object. The destructors are also called when the program exits. Let us have an example:

using System;
using System;
namespace ConsoleApplication1
{
   class Square
   {
      private int side;   
      public Square()
      {
         Console.WriteLine ("The object is created");
      }
     ~Square( )
      { 
             Console.WriteLine ("The object is destroyed");
      }
     public void setSide( int s )
      {
         side = s;
      }
      public int getSide()
      {
         return side;
      }
      static void Main(string[] args)
      {
        Square sq = new Square();      
         sq.setSide(5);
         Console.WriteLine ("The area is: {0}", sq.getSide( ));
         Console.ReadKey ( );
      }
   }
}

Output:
The object is created
The area is: 25
The object is destroyed