In C#, class members are the components that define the behavior and state of a class. They can include fields, properties, methods, events, and constructors. Here’s a brief overview of each:
1. Fields
Fields are variables that hold the state of a class.
{
private string name;
// Field private int age;
// Field
}
2. Properties
Properties provide a flexible mechanism to read, write, or compute the values of private fields.
{
private string name;
// Backing field public string Name
// Property
{ get { return name; } set { name = value; }
}
public int Age { get; set; }
// Auto-implemented property
}
3. Methods
Methods define actions that can be performed by instances of the class.
{
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
4. Constructors
Constructors are special methods that are called when an instance of a class is created. They can initialize fields or properties.
{
public Person(string name, int age)
// Constructor { Name = name; Age = age; }
}
5. Events
Events are a way to provide notifications that something has happened.
{
public event EventHandler NameChanged;
private string name;
public string Name {
get { return name; }
set { name = value; NameChanged?.Invoke(this, EventArgs.Empty); }
}
}
Example Class
Here’s a complete example that combines all these elements:
{
private string name;
// Field
public string Name {
get { return name; }
set { name = value; NameChanged?.Invoke(this, EventArgs.Empty); }
}
// Property
public int Age { get; set; }
// Auto-implemented property
public event EventHandler NameChanged;
// Event
public Person(string name, int age)
// Constructor { Name = name; Age = age; }
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
// Method
}
Summaryn
C# encapsulate the state and behavior of objects. Understanding these members is crucial for effective object-oriented programming in C#.