In the C# programming language, the class and object are the fundamental components of OOP (Object Oriented Programming). They provide the code in a more organized, reusable, and maintainable way. In C#, classes act like a blueprint that defines how objects are structured and behave in the program. On the other hand, objects are instances of classes that are used to hold data and methods to create and manipulate several entities.
C# Classes
In OOP, a class is a fundamental building block that collects the data members and data methods into a single unit. It is a user-defined reference type that acts as a blueprint to create objects. A class keyword is used to create a class in C#.
A class helps in code reusability and portability, which means the same class can be used across different programs without rewriting the code. It also supports encapsulation, which means it hides the internal implementation details of a class and shows only the necessary features to the outside world. It can also contain fields, properties, methods, constructors , and events .
Syntax:
It has the following syntax.
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
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:
The student's name is John
The student's age is 20
Explanation:
In this example, we define the class named Student. Inside this class, we create the methods named DisplayInfo and a member named "name" and "age" that display the details of the student.
After that, we create an object of the class Student and assign the values "John" and 20 to the object's name and age. Finally, we use the Console.WriteLine function to print the output.
C# Class Access Specifiers
In the C# programming language , the access specifiers are used to control access to class members. The access specifier is also known as an access modifier in C#. These are the keywords that are used to limit the accessibility of data members and methods, including 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 object is a run-time entity (such as a chair, a car, a pen, etc.) that is used to represent the features of a class. It is also known as an instance of a class, which defines its structure, behaviour, and identity. It is created in the memory when the program is executed. Objects are used to hold data in fields and can access methods and the properties of the class.
Creating Objects in C#
In C#, once the class is defined in the program, we can easily create its object in the same manner that we define the variable of any other built-in data type . The object is created using the new keyword, which gives memory to the class and returns a reference to it.
Syntax:
It has the following syntax:
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
Let us take an example to define the object in C#.
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:
Car Brand: Toyota
Manufacturing Year: 2022
Explanation:
In this example, we demonstrate how to use the object in C#. First, we create a class named Car. Inside the class, we create the method named ShowDetails.
In the main method, we create an object of the class Car. The brand and year of the item are given the values "Toyota" and 2022. Finally, we use the Console.WriteLine function to print the output.
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 us take an instance of the class that contains two fields: id and name. We create an instance of the class and initialize the object, and then print the value.
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:
501
Alex Parker
Explanation:
In this example, we demonstrate how to use the class and object in C#. First, we create a class named Worker that has two variables, WorkerId and WorkerName. After that, we create the object (w1) of the class (Worker) and assign the value 501 and Alex Parker. Finally, we use the Console.WriteLine function to print the output.
Pass an Object as an Argument into a Method in C#
In the C# programming language, we can pass an object to a method. The method is a code block that only runs when it is called and carries out a specific task. We can pass the data as arguments, and also pass an object as an argument that is an instance of a class.
When we pass an object to a method, the reference to the object is transmitted, and it doesn't create a copy of the object itself. Therefore, any changes made to the object inside the method will also affect the original object outside the method.
Syntax:
It has the following syntax.
// 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 take another example of a C# program where we store and retrieve employee information.
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:
101 John 995000
102 Michael 29700
Explanation:
In this example, we define the class named Staff that contains the variables name, staffid, staffname, staff_salary, along with the method name ShowDetails. After that, we create the objects (staff1, staff2) of the class (Staff) and assign the value. Finally, we are using the Console.WriteLine function to print the output.
Differentiate between the Classes and Objects in C#
Several differences between the classes and objects in C# are as follows.
| 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 are the foundation of the object-oriented programming language. These are the fundamental building blocks that are used to create software applications. A class is a user-defined reference type that works as a blueprint to create an object. In contrast, an object is an instance of a class that contains actual values. They enable us to write code in a more organized, reusable, and maintainable way.
C# Classes and Objects FAQs
1) Define the Classes in C#.
A class is a collection of data members and data methods in a single unit. The class keyword is used to create a class. It implements portability in our program, which means that we can use a class easily from one program to another. It helps in implementing encapsulation, which means hiding the internal details and showing only the necessary details to the outside world.
2) Define the Objects in C#.
An object is a run-time entity that is used to represent the features of a class. It means an object exists in runtime in a program. We can access the features of the class using the object. It is an instance of the class, which is loaded in memory at runtime.
3) Can a Class inherit from multiple classes in C#?
No, multiple inheritance for classes is not supported in C#. However, the class is capable of implementing multiple interfaces.
4) What are the default access modifiers for a class in C#?
Internal Specifier is the default access modifier in a class in C#.
5) Can a Class inherit from another class in C#?
Yes, C# supports single inheritance using the (:) symbol.