The Architecture of a Class in C#
What is Class Architecture in C#?
A class in C# is a blueprint that defines the attributes and behaviors (methods) of objects. It serves as the primary structure for object-oriented programming (OOP) in C#. The architecture of a class defines its fields, methods, properties, and constructors.
Defining a Basic Class in C#
A basic class contains fields, properties, methods, and constructors. These elements work together to encapsulate data and functionality.
Example of a Class:
public class Car
{
// Fields
private string model;
private int year;
// Constructor
public Car(string model, int year)
{
this.model = model;
this.year = year;
}
// Property
public string Model
{
get { return model; }
set { model = value; }
}
// Method
public void DisplayInfo()
{
Console.WriteLine($"Model: {Model}, Year: {year}");
}
}
In this example, the Car
class contains private fields, a constructor for initialization, a property for accessing/modifying the field, and a method to display the car's information.
Key Components of a Class
- Fields: Variables that hold the data of the class.
- Properties: Provide access to fields in a controlled way.
- Methods: Functions that define behaviors of the class.
- Constructors: Special methods to initialize class objects.
Access Modifiers in Class
C# provides access modifiers like public
, private
, protected
, and internal
to control the visibility and accessibility of class members.
Example of Access Modifiers:
public class Car
{
private string model; // private field
public string Model // public property
{
get { return model; }
set { model = value; }
}
}
In this example, the model
field is private, and access is provided via the public Model
property.
Types of Constructors in C#
- Default Constructor: A constructor without parameters.
- Parameterized Constructor: A constructor that accepts parameters.
- Copy Constructor: A constructor that copies data from one object to another.
- Static Constructor: Used to initialize static fields of a class.
Example of Parameterized Constructor:
public class Car
{
private string model;
private int year;
// Parameterized Constructor
public Car(string model, int year)
{
this.model = model;
this.year = year;
}
public void DisplayInfo()
{
Console.WriteLine($"Model: {model}, Year: {year}");
}
}
This example demonstrates a parameterized constructor that initializes the fields model
and year
.
Key Points to Remember
- A class is a blueprint for creating objects in C#.
- Fields store data, while methods define behavior in a class.
- Access modifiers control the visibility of class members.
- Constructors are used to initialize objects in C#.