04 Feb 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:
1 2 3 4 5 6 7 |
class Rectangle { // The data members or class members or member variables or fields double length; double 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:
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:
1 2 3 |
ClassName obj = new ClassName() |
Above, the obj is our object created using the new operator.
Let us see the above syntax and create three objects in C#:
1 2 3 4 5 6 |
// Objects of class Rectangle Rectangle rct1 = new Rectangle(); Rectangle rct2 = new Rectangle(); Rectangle rct3 = new Rectangle(); |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; namespace Demo { class Rectangle { /// The data members or class members or member variables or fields double length; double width; static void Main(string[] args) { // Creating an object rct // Declaring rct of type Rectangle Rectangle rct = new Rectangle(); double area; // Accessing fields using the dot syntax // Set the values of length and width rct.length = 10; rct.width = 12; Console.WriteLine("Length of Rectangle = {0}",rct.length); Console.WriteLine("Width of Rectangle = {0}",rct.width); // Calculating Area of Rectangle area = rct.length * rct.width; Console.WriteLine("\nArea of Rectangle = {0}",area); } } } |
Output
1 2 3 4 5 6 |
Length of Rectangle = 10 Width of Rectangle = 12 Area of Rectangle = 120 |
No Comments