Class and Objects in C#

Class and Objects in C# with Examples

In this article, I am going to discuss Class and Objects in C# with some examples. Please read our previous article before proceeding to this article where we discussed the basics concepts of Object-Oriented Programming. Understanding class and objects in C# is very important for you as a developer. This is because everything in C# is in the form of class and objects. As part of this article, we are going to discuss the following pointers in detail.

  1. Understanding Class and Objects from Layman Point of View.
  2. What is a Class in C#?
  3. Types of classes in C#.
  4. How to create a class in C#?
  5. How to create objects in C#?
  6. Difference between Class and Objects in C#.
Understanding Class and Objects from Layman Point of View.

In simple word, we can define a class is like a blueprint of a specific object. In real-world, each and every object has some color, shape, and functionalities.

For example, if we consider the luxury car Ferrari. Ferrari is an object of the luxury car type. The luxury car is a class that specifies a certain characteristic like speed, color, shape, etc. So any company that makes a car that meets all those requirements is an object of the luxury car type.

For example, every single car of BMW, Lamborghini, and Cadillac are an object of the class called ‘Luxury Car’. Here, ‘Luxury Car’ is a class and every single physical car is an object of the luxury car class.

In the same way, in object-oriented programming, a class defines certain properties, fields, method, etc. That means a class defines the kinds of data and the functionality their objects will have.

What is a Class in C#?

Technically, we can define classes are the user-defined data types which represent both the state and the behavior of an object. The state represents the properties and behavior is the action that objects can perform.

As we already discussed C# is an object-oriented programming language, so the programs are designed using objects and classes. A class is a top-level block that is used for grouping variables and methods for developing logic.

Types of classes in C#

In C# we have below types of classes

  1. Abstract class
  2. Concrete class
  3. Sealed class
  4. Partial class
  5. Static class

We will discuss each of these classes in details in our upcoming articles. In this article, I will give you a brief introduction about class and objects in C#.

We can declare a class by using the following access specifiers that limit the accessibility of classes to other classes, however, some classes do not require any access modifiers.

  1. Public
  2. Private
  3. Protected
  4. Internal
  5. Protected internal

To learn the details of access specifiers please refer to the following article:

Access Modifiers in C#  

Points to remember while working with classes:
  1. Classes are reference type means they hold the object reference that is created dynamically in a heap.
  2. All classes in C# have a base type of System.Object.
  3. In C#, the default access modifier of a class is Internal.
  4.  The default access modifier of methods and variables is Private.
  5.  Directly inside the namespaces declarations of private classes are not allowed.
How to create a Class in C#?

A class definition starts with the keyword class followed by the class name, and the class body enclosed by a pair of curly braces. Following is the general form of a class definition:

Class and Objects in C#

Note:
  1. Access specifiers specify the accessibility for the class members as well as the member type (i.e. class itself). If the access specifier is not mentioned, then the default access specifier for a class type is internal and the default access specifier for the class member is private.
  2. The data type specifies the type of variable, and return type specifies the data type of the data the method returns if any.
How to create an Object in C#?

In C#, Object is a real-world entity, for example, chair, car, pen, mobile, laptop, etc. In other words, we can say that the object is an entity that has state and behavior. Here, state means data and behaviors means functionality.

An object is a runtime entity that is, it is created at runtime.

The object is an instance of a class. All the members of a class can be accessed through the object. To access the class members, we need to use the dot (.) operator. The dot operator links the name of an object with the name of a member of a class.

Let’s see an example to create an object using the new keyword.

Employee e1 = new Employee(); //creating an object of Employee 

In this example, Employee is the type and e1 is the reference variable that refers to the instance of Employee class. The new keyword allocates memory at runtime.

Example:

Let’s see an example of a class that has three fields: id, name, and department. It creates an instance of the class, initializes the object and prints the object value.

namespace ClassObjectDemo
{
    public class Employee
    {
       // by default the class Member are private
        int id; //data member or instance variable    
        String name; //data member or instance variable 
        string department; //data member or instance variable 

        public static void Main(string[] args)
        {
            //creating an object of Employee
            Employee e1 = new Employee();

            //Initializing the Employee Object
            e1.id = 101;
            e1.name = "Pranaya Rout";
            e1.department = "IT";

            //Printing the values
            Console.WriteLine("Employee ID : " + e1.id);
            Console.WriteLine("Employee Name : " + e1.name);
            Console.WriteLine("Employee Department : " + e1.department);

            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}

OUTPUT:

Class and Objects output in C#

Example: The Main() method in another class

Let’s see another example of a class where we are having the Main() method in another class. In such a case, the class must be public and we need to specify the class member as public as shown in the below example.

namespace ClassObjectDemo
{
    public class Employee
    {
        public int id; //data member or instance variable    
        public String name; //data member or instance variable 
        public string department; //data member or instance variable    
    }

    public class EmployeeTest
    {
        public static void Main(string[] args)
        {
            //creating an object of Employee
            Employee e1 = new Employee();

            //Initializing the Employee Object
            e1.id = 101;
            e1.name = "Pranaya Rout";
            e1.department = "IT";

            //Printing the values
            Console.WriteLine("Employee ID : " + e1.id);
            Console.WriteLine("Employee Name : " + e1.name);
            Console.WriteLine("Employee Department : " + e1.department);

            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}

OUTPUT:

Class and Objects output in C#

Example: Initialize and Display data through a method

Let’s see another example where we are initializing and displaying an object through the method.

namespace ClassObjectDemo
{
    public class Employee
    {
        public int id; //data member or instance variable    
        public String name; //data member or instance variable 
        public string department; //data member or instance variable    
        
        public void InsertData(int ID, String Name, string Department)
        {
            id = ID;
            name = Name;
            department = Department;
        }
        public void DisplayData()
        {
            Console.WriteLine("Employee ID : " + id);
            Console.WriteLine("Employee Name : " + name);
            Console.WriteLine("Employee Department : " + department);
        }
    }

    public class EmployeeTest
    {
        public static void Main(string[] args)
        {
            //creating two objects of Employee class
            Employee e1 = new Employee();
            Employee e2 = new Employee();

            //Initializing the Employee Object e1 using method
            e1.InsertData(101, "Pranaya Rout", "IT");

            //Initializing the Employee Object e2 using method
            e2.InsertData(102, "Mitali Rout", "HR");

            //Printing the values of e1 using method
            e1.DisplayData();

            //Printing the values of e2 using method
            e2.DisplayData();

            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}

OUTPUT:

Understanding Class in C#

Difference between Class and Objects in C#

Many programmers still get confused by the difference between class and object in c#. In object-oriented terminology, a Class is a template for Objects and every Object must belong to a Class. The terms “Class” and “Object” are related to one another and each term holds its own distinct meaning. Let us understand this with an example. Please have a look at the following image.

Class and Objects in C#

Suppose you have a class called “Employee“. All the Employees have an id, name, and department, etc. and these could be the attributes (properties or fields) of your Employee class.

You can also add some methods (functions) that would be common to all Employees like InsertData and DisplayData to insert and display the Employee Data.

So, the idea you really want to enforce in your own mind is that the ‘template‘ of Employee does not change. Each Object was built from the same template (Class) and therefore contains the same set of components (methods and properties /fields).

All Objects share the same copy of the member functions (methods), but maintain a separate copy of the member data (Properties or fields).

For example: if we create two employees, let’s say e1 and e2, then both e1 and e2 are Employees, so they can be classified as belonging to the Employee class. Both have the same methods (InsertData and DisplayData) but different in models (properties or fields)

In this article, I try to explain Class and Objects in C# with some examples. I hope you understood class and objects in C#. In the next article, I am going to discuss Constructors in C# and its types in details with examples.

Leave a Reply

Your email address will not be published. Required fields are marked *