C# Class And Object

In C#, the class and object serve as the foundational elements of OOP (Object-Oriented Programming), offering a structured and reusable approach to coding. Classes in C# function as a template outlining the structure and behavior of objects within the program. Conversely, objects represent specific instances of classes, enabling the storage of data and functions to generate and control multiple entities.

The styling code snippet defines a placeholder diagram with a linear gradient background, border radius, padding, margin, and centered text alignment. The placeholder icon within the diagram has a font size of 3rem and a margin bottom of 10px. The placeholder text is styled with a color of #9ca3af and a font size of 1rem.

C# Classes

In Object-Oriented Programming (OOP), a class serves as a foundational component that consolidates data members and methods into a cohesive entity. It represents a user-defined reference type that functions as a template for generating objects. The class keyword is employed to define a class in the C# programming language.

A class facilitates code reusability and portability, enabling its utilization across various programs without the need for rewriting. Additionally, it promotes encapsulation by concealing the internal workings of a class and revealing only essential functionalities to external entities. A class may encompass fields, properties, methods, constructors, and events.

Syntax:

It has the following syntax.

Example

class Class_Name

{

    public int data; // Data member

    public void Display()

    {

        // code to be executed

    }

}

In this syntax,

  • Data Members: The data members are the variables that are defined inside the class of the program.
  • Data Method: The data method is the functions that are also defined in the class of the program that operate on the data members.
  • Access Specifiers: These are utilized to define the visibility and access of a class and its members. These specifiers access the class, field, property, and method.
  • C# Class Example

Let us take an example to define a class in C#.

Example

Example

using System;

namespace Example

{

    class Student

    {

        public string name;

        public int age;

        public void DisplayInfo()

        {

            Console.WriteLine("The student's name is " + name);

            Console.WriteLine("The student's age is " + age);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Student s1 = new Student();

            s1.name = "John";

            s1.age = 20;

            s1.DisplayInfo();

        }

    }

}

Output:

Output

The student's name is John

The student's age is 20

Explanation:

In this instance, we establish the class called Student. Within this class, we define the functions named ShowDetails and an attribute named "name" and "age" which exhibit the particulars of the student.

Following this, we instantiate a Student class object and set the attributes "John" and 20 as the values for the object's name and age respectively. Subsequently, we utilize the Console.WriteLine method to display the result.

C# Class Access Specifiers

In C#, access specifiers are essential for managing access to class elements. These specifiers, also referred to as access modifiers in C#, consist of keywords that define the extent of accessibility for data members and methods, such as protected, private, public, and internal.

There are mainly four types of access specifiers in C#.

  • Public Specifier: In C#, the public is a more flexible specifier. The public members of a class will be accessible from anywhere in the program.
  • Private Specifier: The private members are the more restrictive specifiers in C#. The data members of a class will be accessible inside the code block where they were declared.
  • Protected Specifier: The protected members of the class will be accessible within the same class and also inside its derived classes.
  • Internal Specifier: The internal specifiers are of assembly-level specifiers. The internal member of the class that can be accessed within the same assembly.

To Read More: Access Modifiers in C#

C# Object

An entity at run-time, like a chair, a car, or a pen, serves to embody the characteristics of a class. Referred to as an instance of a class, it delineates the structure, behavior, and distinct identity. Generation of an object in memory occurs during program execution. Objects function to store information in fields and have the ability to interact with methods and attributes of the class.

The CSS code snippet below demonstrates the styling for a placeholder diagram:

Example

.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }

Creating Objects in C#

Once the class is declared in a C# program, generating an instance of it follows a similar approach to declaring a variable of a standard data type. By employing the new keyword, memory is allocated to the class, and a reference to it is provided.

Syntax:

It has the following syntax:

Example

ClassName objectName = new ClassName();

In this syntax,

  • ClassName: It defines the name of the class.
  • ObjectName: It refers to the name of the object of a class that can be created.
  • new: The new keyword is used to make a new object in memory.
  • C# Object Example

Consider an example to illustrate the concept of an object in C#.

Example

Example

using System;

namespace Example

{

    // create a class

    class Car

    {

        // Data members

        public string Brand;

        public int Year;

        // Method

        public void ShowDetails()

        {

            Console.WriteLine("Car Brand: " + Brand);

            Console.WriteLine("Manufacturing Year: " + Year);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            // object

            Car myCar = new Car();

            // Assigning values

            myCar.Brand = "Toyota";

            myCar.Year = 2022;

            // Accessing method using object

            myCar.ShowDetails();

        }

    }

}

Output:

Output

Car Brand: Toyota

Manufacturing Year: 2022

Explanation:

In this instance, we showcase the utilization of the object in C#. Initially, we establish a class called Car. Within this class, we define a function named ShowDetails.

In the primary function, we instantiate an instance of the Car class. The manufacturer and production year of the object are assigned the values "Toyota" and 2022 respectively. Ultimately, the Console.WriteLine method is employed to display the result.

Characteristics of an Object:

The several characteristics of an object are as follows:

  • Identity: Every object has a unique identity, even if multiple objects have the same values for their properties.
  • State: Data members of the class can represent the state of the object. It refers to the properties or data stored within the object.
  • Behaviour: The behaviour of an object is represented as a data method of the class. It defines what operations the object can perform.
  • C# Classes and Objects Example

Let's consider a scenario where we have a class with two attributes: id and name. We instantiate the class, set values for the object, and subsequently display the values.

Example

Example

using System;

class Worker  // define the class 

{

    public int WorkerId;       // variable name

    public string WorkerName;  

}

class Program

{

    static void Main(string[] args)

    {

        Worker w1 = new Worker();  // Object 

        w1.WorkerId = 501;         // Assigning values

        w1.WorkerName = "Alex Parker"; 

        Console.WriteLine(w1.WorkerId);      // Display Worker ID

        Console.WriteLine(w1.WorkerName);    // Display Worker Name

    }

}

Output:

Output

501

Alex Parker

Explanation:

In this instance, we showcase the utilization of classes and objects in C#. Initially, a class called Employee is established with two attributes, EmployeeID and EmployeeName. Subsequently, an object (emp1) of the Employee class is instantiated with the values 501 and Alex Parker. Ultimately, the Console.WriteLine method is employed to display the result.

Pass an Object as an Argument into a Method in C#

In C# programming, it is possible to send an object to a function. This function represents a set of instructions that executes only when invoked to perform a particular operation. Data can be transmitted as parameters, including an object that represents a class instance.

When an object is passed to a method, it transmits a reference to the object rather than duplicating the object itself. Consequently, modifications to the object within the method will impact the initial object located outside the method as well.

Syntax:

It has the following syntax.

Example

// Creating the testing object

Test t1 = new test(6);

// passing an object as an argument

t1.PassObj(t1);

C# pass an object as an argument in a method Example

Let's consider a different instance of a C# program that deals with storing and fetching employee details.

Example

Example

using System;

class Staff

{

    public int staff_Id;          // variable name

    public string staff_name;     

    public float staff_salary;

    // function name and parameters

    public void SetDetails(int id, string name, float salary)

    {

        staff_Id = id;

        staff_name = name;

        staff_salary = salary;

    }

    // function name

    public void ShowDetails()

    {

        Console.WriteLine(staff_Id + "  " + staff_name + "  " + staff_salary);

    }

}

class Program

{

    static void Main(string[] args)

    {

        Staff staff1 = new Staff();  // object name and class

        Staff staff2 = new Staff();

        staff1.SetDetails(101, "John", 995000);

        staff2.SetDetails(102, "Michael", 29700);

        staff1.ShowDetails();

        staff2.ShowDetails();

    }

}

Output:

Output

101  John  995000

102  Michael  29700

Explanation:

In this instance, we are outlining the class called Employee which includes the attributes fullname, employeeid, job_title, salary, and the function named DisplayInfo. Subsequently, instances (emp1, emp2) of the Employee class are instantiated and initialized. Ultimately, the Console.WriteLine method is employed to display the results.

Differentiate between the Classes and Objects in C#

Some variances between classes and objects in C# are outlined below.

Features Classes Objects
Definition Class is a collection of data members and data methods in a single unit. Objects are instances of the class.
Syntax class Class_Name ClassName c1 = new ClassName
Uses It is mainly used for concepts and models. It is mainly used for real-world entities, such as data and functionality.
Representation It represents a general concept or type. It represents a specific instance of the class.
Memory Allocation In C# classes, no memory is allocated until an object is created. Memory for a class is allocated only when an object is created.

Important Points about Classes and Objects

Several important points about classes and objects in C# are as follows:

  • Classes and Objects are the fundamental concepts of OOP in C#. We can get the different aspects like inheritance , encapsulation , and abstraction using these classes and objects.
  • When we create an object, each object has a different identity that sets it apart from other things.
  • We can use the destructor to end the instance in order to reduce the memory usage.
  • Classes and Objects are used to implement portability in our program, which means we can use a class easily from one program to another program.
  • Conclusion

In C#, classes and objects form the basis of the object-oriented programming paradigm. These components serve as the essential elements for constructing software applications. A class in C# represents a custom reference type that serves as a template for object creation. Conversely, an object represents a specific occurrence of a class with concrete data values. Classes and objects promote structured, reusable, and easily maintainable code development practices.

C# Classes and Objects FAQs

1) Define the Classes in C#.

A class represents a cohesive unit comprising data attributes and methods. The class keyword is essential for defining a class. It promotes program portability, enabling seamless utilization of a class across different programs. Furthermore, it facilitates encapsulation, allowing the concealment of internal workings while exposing only essential information externally.

2) Define the Objects in C#.

An object is a dynamic entity that embodies the characteristics of a class. This signifies that an object is present during the execution of a program. By utilizing the object, we can interact with the attributes of the class. Essentially, it is a concrete occurrence of the class that is stored in memory while the program is running.

In C#, is it possible for a class to inherit from multiple classes?

No, C# does not support multiple inheritance for classes. Nevertheless, classes can implement multiple interfaces.

4) What are the standard access modifiers for a class in C#?

The default access modifier in a class in C# is Internal Specifier.

5) Can a Class inherit from another class in C#?

Yes, C# enables single inheritance through the (:) symbol.

Input Required

This code uses input(). Please provide values below: