C# Object and Class
Syntax
class ClassName
{
// Fields, properties, methods, and events go here.
}
Example
class Car
{
public string model;
public string color;
public int price;
public void Start()
{
Console.WriteLine("Car started");
}
public void Stop()
{
Console.WriteLine("Car stopped");
}
}
Output
No output as the above code just defines a class.
Explanation
In C#, an object is an instance of a class. A class is a template or blueprint that describes the properties, methods, and events that an object of that class can have. To create an object of a class, you first need to define the class, and then you can create an instance of the class by using the new
operator.
A class is defined using the class
keyword followed by the name of the class, and the class body enclosed in curly braces. The class body can contain fields, properties, methods, and events.
Fields are variables that belong to the class and can hold data. Properties are special methods that allow access to the fields of the class. Methods are functions that can perform actions and return values. Events are used to signal that something has happened in the class.
To create an object of a class, you can use the new
operator followed by the name of the class, and assign the object to a variable of the class type.
Use
Classes are used to define objects in C#. They provide a way to encapsulate and organize code by grouping related fields, properties, methods, and events together into a single unit.
In C#, you can create as many instances of a class as you need. Each instance of the class is a separate object that has its own set of fields, properties, and methods.
Important Points
- A class is a template or blueprint for creating objects.
- Fields, properties, methods, and events can be defined inside a class.
- To create an object of a class, use the
new
operator followed by the name of the class. - Classes provide a way to encapsulate and organize code.
Summary
In C#, classes are used to define objects. Classes contain fields, properties, methods, and events, which define the behavior and characteristics of objects created from the class. To create an object of a class, you use the new
operator followed by the name of the class. Classes play an important role in encapsulating and organizing code into reusable units.