Class
In C#, a class is a user-defined blueprint or prototype from which objects are created. It represents a group of related properties and methods that define the behavior of the objects.
Structure of a C# Class
A C# class typically consists of:
- Fields: Variables that hold data.
- Properties: Accessors for fields.
- Methods: Functions that define behavior.
- Constructors: Special methods for initializing objects.
- Events: Notifications sent by an object.
Object
In C#, an object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created. An object is a real-world entity, like a car, house, or employee, that has state and behavior. The class defines the properties (state) and methods (behavior) that the objects created from the class will have.
Creating an Object
To create an object of a class, you use the new keyword followed by the class name and any required arguments for the constructor
Difference between object and class
Class | Object |
Class is the blueprint of an object. It is used to declare and create objects. | Object is an instance of class. |
No memory is allocated when a class is declared. | Memory is allocated as soon as an object is created. |
A class is a group of similar objects. | Object is a real-world entity such as book, car, etc. |
Class is a logical entity. | Object is a physical entity. |
Class can only be declared once. | Object can be created many times as per requirement. |
Example of class can be car. | Objects of the class car can be BMW, Mercedes, jaguar, etc. |