C# Class and Object
In this tutorial, you will learn about the concept of classes and objects in C# with the help of examples.
C# is an object-oriented program. In object-oriented programming(OOP), we solve complex problems by dividing them into objects.
To work with objects, we need to perform the following activities:
create a class
create objects from the class
C# Class
Before we learn about objects, we need to understand the working of classes. Class is the blueprint for the object.
We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. We can build a house based on these descriptions. House is the object.
Like many houses can be made from the sketch, we can create many objects from a class.
Create a class in C#
We use the class keyword to create an object. For example,
Here, we have created a class named ClassName.
A class can contain
fields - variables to store data
methods - functions to perform specific tasks
Let's see an example,
In the above example,
Dog
- class namebreed
- fieldbark() -
method
Note: In C#, fields and methods inside a class are called members of a class.
C# Objects
An object is an instance of a class. Suppose, we have a class Dog. Bulldog, German Shepherd, Pug are objects of the class
Creating an Object of a Class
In C#, here's how we create an object of the class.
Here, we have used the new
keyword to create an object of the class. And, obj
is the name of the object.
Now, let us create an object from the Dog
class.
Now, the bullDog
object can access the fields and methods of the Dog
class.
Access Class Members using Object
We use the name of objects along with the . operator to access members of a class. For example,
In the above program, we have created an object named bullDog
from the Dog
class. Notice that we have used the object name and the . (dot operator) to access the breed
field and the bark()
method.
Creating Multiple Objects of a Class
We can create multiple objects from the same class. For example,
In the above example, we have created two objects: sheeran
and taylor
from the Employee
class.
Here, you can see both the objects have their own version of the department field with different values.
Why Objects and Classes?
Suppose you want to create a game that has hundreds of enemies and each of them has fields like health
, ammo
, and methods like shoot()
and run()
.
With OOP we can create a single Enemy
class with required fields and methods. Then, we can create multiple enemy objects from it.
Each of the enemy objects will have its own version of health
and ammo fields
. And, they can use the common shoot()
and run()
methods.
Now, instead of thinking of projects in terms of variables and methods, we can think of them in terms of objects.
This helps to manage complexity as well as make our code reusable.
Last updated