Class in C#

There are many definitions of class such as

  • A class is a group of related methods and variables.
  • A class is user define data type.
  • A class is a template for creating object.
  • Class is a blueprint of an object.
Class is reference type. Therefore objects of class are garbage collected. Class defines the properties and behavior.

In general, variables and methods are two important constituents of classes. Apart from variables and methods a class can contain constant, constructors, destructors, properties, events, delegates, and operators. Class can be declared as public, protected internal, protected, internal, or private. Members of class are by default private. In C#, you can perform only single inheritance. You cannot inherit more than one class at a time but a class can implement more than one interface.

Classes are declared by using the class keyword.

public class Employee
{
    //Fields, properties, methods and events, you can write here...
}


Object of the class is created by using new keyword.

Employee obj=new Employee();

Example

using System;
namespace ConsoleApplication1
{
    public class Employee
    {
         int EmpID;
         string Name;
         string Address;

         //Default Constructor
         public Employee()
         {
             EmpID = 0;
             Name = "N/A";
             Address = "N/A";
         }
        // Public Properties
        public int ID
         {
             get { return EmpID; }
             set { EmpID = value; }
         }
        public string empName
        {
            get { return Name; }
            set { Name = value; }
        }
        public string empAddress
        {
            get { return Address; }
            set { Address = value; }
        }

        // Methods
        public void getData()
        {
            Console.WriteLine("Enter Employee ID");
            ID =Convert.ToInt32( Console.ReadLine());
            Console.WriteLine("Enter Employee Name");
            empName = Console.ReadLine();
            Console.WriteLine("Enter Employee Address");
            empAddress = Console.ReadLine();
        }
        public void showData()
        {
            Console.WriteLine("Employee ID\t"+EmpID);
            Console.WriteLine("Employee Name\t" + empName);
            Console.WriteLine("Employee Address\t" + empAddress);
        }
    }
    class Program
    {        
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.getData();
            emp.showData();
            Console.ReadLine();
        }
    }
}


The new operator dynamically allocates memory for an object. The objects of class are totally separated with each other.

Generics

Generics are, one of the most powerful features of C#. It enables you to do type-safe programming. Generics are similar to C++ template concept. Generics enable you to create a class that works with different types of data. You can create your own generic interfaces, classes, methods, events, and delegates.

Generic classes have type parameters. It provides maximize code reuse, type safety, and performance.

Let us take one example, and understand why generics are important in programming.

Suppose that we have to compare two integer values. If the given values are equal than return true else return false. Now we have to compare string data also, then again you will create a new method to compare string value.

class CompareDemo
    {
        public bool CompareType(int x, int y)
        {
            if (x.Equals(y))
                return true;
            else
                return false;
        }
        public bool CompareType(string x, string y)
        {
            if (x.Equals(y))
                return true;
            else
                return false;
        }
    }


Suppose that after some time requirement has been changed. Now you have to compare other data types like decimal, double and objects etc. then we need to create other methods to compare these data type. Creating same type of method again and again is tedious process.

We can solve this problem with use of generics.

Example

using System;
namespace ConsoleApplication1
{
    class CompareDemo<T>
    {
        public bool CompareType(T x, T y)
        {
            if (x.Equals(y))
                return true;
            else
                return false;
        }
    }
    class Program
    {        
      static void Main(string[] args)
      {
          CompareDemo<string> strObj = new CompareDemo<string>();
          bool strResult = strObj.CompareType("DEMO", "DEMO");
          Console.WriteLine("Generic string compare result:=" + strResult);
          CompareDemo<int> intObj = new CompareDemo<int>();
          bool intResult = intObj.CompareType(10, 20);
          Console.WriteLine("Generic integer compare result:=" + intResult);          
          Console.ReadLine();
      }
    }
}


Output:

Generic string compare result: =True
Generic integer compare result: =False

In the above example we created the class CompareDemo<T> with the input parameter T. The input parameter T will automatically converted with specified type while creating the object.

CompareDemo<string> strObj = new CompareDemo<string>();

Because we passed T as a string the CompareType method will accept only a string type of parameter.

Same thing will also do with integer value, if we pass integer type.

A Generic Class with Two Type Parameters.

using System;
namespace ConsoleApplication1
{
    class GenClass<T, V>
    {
        T var1;
        V var2;
        // Constructor has parameters of type T and V.
        public GenClass(T o1, V o2)
        {
            var1 = o1;
            var2 = o2;
        }
        // Show types of T and V.
        public void showData()
        {
            Console.WriteLine("Type of T is " + typeof(T));
            Console.WriteLine("Type of V is " + typeof(V));
        }
        public T getVar1()
        {
            return var1;
        }
        public V GetVar2()
        {
            return var2;
        }
    }   
    class Program
    {        
      static void Main(string[] args)
      {
          GenClass<int, string> genObj =new GenClass<int, string>(25, "WELCOME");
          genObj.showData();
          int v = genObj.getVar1();
          Console.WriteLine("value: " + v);
          string str = genObj.GetVar2();
          Console.WriteLine("value: " + str);
          Console.ReadLine();
      }
    }
}


Output:

Type of T is System.Int32
Type of V is System.String
Value: 25
Value: WELCOME

Please note that how we declared the class
GenClass<T, V>

It has two type parameters: T and V, separated by a comma. When we create the object of the class we must specify the two type parameter. You can pass any type in place of T and V generic parameter.