Difference between classes and objects
(O-1-1) |
A class is a template for objects, and an object is an instance of a class . Now we will get to know much about objects and classes separately(O-1-1).
Classes in C#
A class is a blueprint or template that defines the characteristics and behaviors of a certain type of object.
It encapsulates data and functions that operate on that data and allows for the creation of multiple instances of that class, each with its own unique state and behavior.
Classes provide a way to organize and structure code in a logical and reusable way. They can contain properties, methods, events, and other types of members that define the class's behavior.
To create a class in C#, you use the class keyword followed by the class name. Here's an example(O-1-2):
(O-1-2) |
Objects in C#
An object is an instance of a class that has its own unique state and behavior. It is created using the new keyword followed by the name of the class and any arguments that the class constructor requires.
Once an object is created, you can access its properties and methods using dot notation. For example, if you have a Person object named person1, you can set its Name property using person1.Name = "Tharindu";.
Here's an example of creating two objects of the Person class and using them(O-1-3):
(O-1-3) |
Code Explanation of the above example(O-1-3)
The 2 Objects(persion1 and persion2)
This above code creates two objects of the Person class named person1 and person2.
persion1 Object
For person1, the Name property is set to "Tharindu" and the Age property is set to 20.
persion2 Object
For person2, the Name property is set to "john" and the Age property is set to 25.
إرسال تعليق