C# Classes and Objects

In this lesson, we will understand what is a class and object in C#. With that, we will also see some examples of creating classes and objects. We have covered the following topics:

  • What is a Class
  • What is an Object
  • How to create an Object
  • Example – Classes & Objects

What is a class

In C#, a class is a template for an object, whereas an object is an instance of a class. Consider, a class as a blueprint.

To create a class is to declare in C#. At first, to declare a class, use the class keyword in C#. The class is a reserved word in C#.

Let us now see how to define a class in C#. In the below example, the class members are length and width:

What is an Object

An object is an instance of a class i.e., an object is created from a class. Object represents real-life entities, for example, a Bike is an object. Object has State, Behavior, and Identity:

  • Identity: Name of Bike
  • State (Attributes): The data of object Bike i.e., Color, Model, Weight, etc.
  • Behavior (Methods): Behavior of object Bike like to Drive, Brake

Let us now see the representation, with Bike as an object:

CSharp Objects

Create an Object

An object is a runtime entity with state and behavior. To create an object in C#, we use the new operator. The syntax is as follows:

Above, the obj is our object created using the new operator.

Let us see the above syntax and create three objects in C#:

Example: Classes and Objects

Let us see the complete example to create a class and object. In this example, we will also learn how to access the fields of the class using the dot syntax:

Output

C# Constructors
C# Methods
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading