Class and Object Concepts
Classes and objects are fundamental concepts in object-oriented programming (OOP), and C# is a fully object-oriented language. Understanding classes and objects will enable you to design more complex and flexible programs.
Classes
Generally, a class declaration contains only a keyword class, followed by an identifier(name) of the class. But there are some optional attributes that can be used with class declaration according to the application requirement. In general, class declarations can include these components, in order:
- Modifiers: A class can be public or internal etc. By default modifier of the class is internal.
- Keyword class: A class keyword is used to declare the type class.
- Class Identifier: The variable of type class is provided. The identifier(or name of the class) should begin with an initial letter which should be capitalized by convention.
- Base class or Super class: The name of the class’s parent (superclass), if any, preceded by the : (colon). This is optional.
- Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded by the : (colon). A class can implement more than one interface. This is optional.
- Body: The class body is surrounded by { } (curly braces).
In C#, a class is a blueprint for creating objects. It defines a set of properties (data) and methods (behavior) that the created objects will have. Here's an example of a class:
public class Dog { // Properties public string Name { get; set; } public int Age { get; set; } // Methods public void Bark() { Console.WriteLine("Woof!"); } }
In this example, Dog is a class with two properties, Name and Age, and one method, Bark.
Objects
It is a basic unit of Object-Oriented Programming and represents real-life entities. A typical C# program creates many objects, which as you know, interact by invoking methods. An object consists of:
- State: It is represented by attributes of an object. It also reflects the properties of an object.
- Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects.
- Identity: It gives a unique name to an object and enables one object to interact with other objects.
An object is an instance of a class. It has a state stored in its properties and behavior defined by its methods. Here's how to create an object of the Dog class:
Dog myDog = new Dog();
You can set the properties of the object and call its methods like this:
myDog.Name = "Fido"; myDog.Age = 3; myDog.Bark(); // Prints "Woof!" to the console
Each object is a separate instance with its own set of properties. You can create another Dog object with different properties:
Dog anotherDog = new Dog(); anotherDog.Name = "Spot"; anotherDog.Age = 5;
Reference: https://www.geeksforgeeks.org/c-sharp-class-and-object/