Overview of C# Classes
What is a Class?
- A class serves as a blueprint for creating objects in C#.
- It encompasses properties (attributes) and methods (functions) that the objects instantiated from the class can utilize.
Key Concepts
1. Defining a Class
- A class is defined using the
class
keyword. - Example:
public class Car
{
// Properties
public string Model;
public string Color;
// Method
public void Drive()
{
Console.WriteLine("The car is driving.");
}
}
2. Creating an Object
- Objects are instances of classes.
- To create an object, use the
new
keyword followed by the class name. - Example:
Car myCar = new Car();
3. Accessing Properties and Methods
- You can access properties and methods of a class using the dot (
.
) operator. - Example:
myCar.Model = "Toyota";
myCar.Color = "Red";
myCar.Drive(); // Output: The car is driving.
4. Constructors
- A constructor is a special method that initializes an object upon creation.
- It shares the same name as the class and does not return a value.
- Example:
public class Car
{
public string Model;
public string Color;
// Constructor
public Car(string model, string color)
{
Model = model;
Color = color;
}
}
Car myCar = new Car("Honda", "Blue");
5. Encapsulation
- Encapsulation refers to restricting access to specific components of an object.
- Access modifiers such as
public
, private
, and protected
can be employed to control visibility.
6. Inheritance
- Inheritance allows a class to inherit properties and methods from another class.
- Example:
public class Vehicle
{
public void Start()
{
Console.WriteLine("Vehicle starting...");
}
}
public class Car : Vehicle
{
public void Drive()
{
Console.WriteLine("Car is driving.");
}
}
Car myCar = new Car();
myCar.Start(); // Inherited method
myCar.Drive();
Summary
- Classes are fundamental to object-oriented programming in C#.
- They facilitate the organization of code into manageable sections by grouping related properties and methods.
- A solid understanding of classes is essential for developing robust C# applications.