C# is an object-oriented programming language and classes and objects are the fundamental components of OOP’s. Everything in C# is built upon classes and objects. Let us learn classes and objects with an example.
C# Class
A class is a user-defined blueprint or prototype for creating Objects. We can say that it is a template for creating objects for a class.
A class can have fields, methods, constructors, etc and these members can be accessed and used by creating an instance of that class that is an object.
Example for defining a class with few fields and methods in C#.
1 2 3 4 5 6 7 8 9 10 11 12 | public class Rectangle { //field int length, breadth; int area; // method public void area() { area = length * breadth; } } |
The definition of the class starts with the keyword class followed by a class name. The body of the class is enclosed within the curly brace. All the members of the class are declared within the body of the class as shown above.
C# Object
Objects are real-world entities. Example bike, Lamp, pen, table, etc. It is an instance of a class that has states and behavior. It can be physical and logical.
The Class members are accessed by creating an object of that class and is a runtime entity created at runtime.
To create an object of a class we use the keyword new.
1 2 | //creating an object of class Rectangle Rectangle rect = new Rectangle(); |
In the above code, Rectangle is a type and rect is a reference variable that refers to the instance of the Rectangle class. And the new keyword allocates the memory at runtime in a program.
Example1: C# Class and Object
Let see an example where we create a class Rectangle and have a method calculate the area and also display the area value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | using System; public class Rectangle { //field int length = 2, breadth = 3; int area; // method public void areaFunc() { area = length * breadth; Console.WriteLine("Area: {0}", area); } public static void Main(string[] args) { Rectangle rect = new Rectangle(); //object rect.areaFunc(); } } |
Output:
Area: 6
Example1: C# Class and Object
In the example below, we will put the main method at the different classes and create multiple objects for the Student class. Also, display the student information.
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; public class Student { //field int roll = 2; String name; //Constructor public Student (int r, String str) { this.roll = r; this.name = str; } // method public void display() { Console.WriteLine("Roll: {0}, Name: {1}", roll, name); } } class StudentInfo { public static void Main(string[] args) { Student std1 = new Student(1, "John Mac"); //object Student std2 = new Student(2, "Ryan Blanc"); //object std1.display(); std2.display(); } } |
Output:
Roll: 1, Name: John Mac
Roll: 2, Name: Ryan Blanc
Also, a constructor is included in order to initialize the class field.