C# Classes Tutorial For Beginners With Examples

A class defines a type. Thus, it allows custom types to be created in a C# program. A class consists of variables, constants, methods, properties and events.

Syntax of a Class

C# classes have a simple syntax. The class keyword is used to declare a class.
<access modifier> class <class name>
{

}             
  • Access modifier: A C# class can have an access modifier which specifies how a class can be accessed. More about access modifiers will be covered in the later part of this tutorial.
  • Class name: Class name is used to identify a class.

Creating a Class

In C#, class keyword is used to declare a class and the class name follows this keyword. In the below example since public is used as an access modifier so anyone can create an object of this class.
    public class Employee
    {
        //Variables

        //Methods

        //Events
    }        
    

Creating Class instances

To use a class in a program an instance of a class has to be created. Class instances are also called as objects. To create an object new keyword should be used.
    Employee employeeObject = new Employee ();


Members of a Class

Classes have members that define their data and behavior. Fields, constantsmethodsproperties and events are considered as members of a class.
variable declared at the class level is called as instance variable or field .
    public class Employee
    {
        string address;

        void UpdateAddress(string newAddress)
        {
            address = newAddress;
        }
    }
        

Static Classes

A class that cannot be instantiated is a static class.
Static class should be used when the purpose is to work on the input parameters and not to get/set any instance fields.
    public static class Robot
    {            
        public static int Add(int x, int y)
        {
            return x+y;
        }
    }
        
A static class can only contain static members and the members of a static class are accessed using the class name directly.
    int result = Robot.Add(1, 2);
        
A static class remains in memory throughout the life time of the application domain in which the program runs.

Static Members

Non-static classes can have static members. Static members are called by using the class name.
Even if multiple instances of a class has been created there is always one copy of a static member in memory.
    class Program
    {        
        public class Robot
        {
            private static int dimension;
            
            public static int Add(int x, int y)
            {
                return x+y;
            }

            public int Increment()
            {
                dimension = dimension + 1;

                return dimension;
            }
        }

        static void Main(string[] args)
        {
            //Works fine
            int result = Robot.Add(1, 2);            
            Console.WriteLine(result);

            //Compile error
            result = Robot.Increment();
            Console.WriteLine(result);

            Console.ReadLine();
        }
    }
        

Constructors

A Constructor is a special type of class or struct member that is called every time an object of a class or struct is created.
A class or struct can have multiple constructors with different parameters. However, structs cannot have parameter less constructors. Constructors are useful when default values are to be set in a class or struct.
As shown below, constructor name should always be same as a class or struct name. BelowEmployee() is a parameter less constructor and Employee(string defaultName) is a parameterized constructor.
        
    public class Employee
    {
        public string name;
        private string employeeNumber;

        //Constructor
        public Employee()
        {
            employeeNumber = "A0000";
        }

        //Constructor
        public Employee(string defaultName)
        {
            name = defaultName;
        }
    }
            
Constructors can be marked as privatepublicinternalprotected and protected internal. These are called as Access modifiers. We will deal with these in the next chapter.
private constructors are used to prevent any instance of a class from being created.
There is a special type of constructor called as static constructor. These constructors are used to initialize members only once or to perform any other action only once. It is also used to initialize static data.

Destructors

A Destructor is used to free up unmanaged resources used in a class.
References to C++, Win32 or COM components are not managed by .NET Framework. These type of resources are unmanaged resources.
Destructors are used only in classes and cannot be used in structs.
    class Employee
    {
       //Constructor
       public Employee() 
        {
            Console.WriteLine("Constructor is called.");
        }

        //Destructor
        ~Employee()
        {
            Console.WriteLine("Destructor is called.");
        }

        static void Main(string[] args)
        {
            Employee emp = new Employee();

            Console.ReadLine();
        }
    }
        
Destructors do not have access modifiers or parameters and its name should be same as class name prefixed with a tilde sign(~).

Nested Classes

Classes can be nested in C#.
Below Traits class is nested inside Employee class.
    public class Employee
    {
        void Employee()
        {

        }

        public class Traits
        {
            void Traits()
            {

            }
        }
    }
        
To access a nested class dot (.) Operator should be used.
    Employee emp = new Employee();

    Employee.Traits traits = new Employee.Traits();
        

Abstraction in C#:

Abstraction is the ability to take a real world concept and represent that concept in a program. It is one of the fundamentals of Object Oriented Programming(OOP).

Employee class shown in this chapter is an example of abstraction as the concept is taken from a real world employee.

Abstract Class

A class that is abstract cannot be instantiated. The abstract class is discussed under the inheritance chapter.