C# Class Members - Complete Guide
Introduction to Class Members
Class members in C# define the structure, data, and behavior of a class. They include fields, properties, methods, events, constructors, and nested types. Each member can have an access modifier that controls how it can be accessed from other parts of the code.
Understanding class members is essential in object-oriented programming because they allow you to encapsulate state and functionality inside objects, making programs more modular and maintainable.
Types of Class Members
C# provides multiple kinds of class members, each serving a different purpose. The example below shows common types of members in a single class:
Example
using System;
namespace ClassMembersExample
{
public class Person
{
// Field (private backing data)
private string name;
// Property (public access to data)
public int Age { get; set; }
// Method (behavior)
public void Greet()
{
Console.WriteLine($"Hello, my name is {name} and I am {Age} years old.");
}
// Constructor (initialization)
public Person(string name, int age)
{
this.name = name;
Age = age;
}
// Event (notification mechanism)
public event EventHandler AgeChanged;
// Nested class (type inside another class)
public class Address
{
public string Street { get; set; }
public string City { get; set; }
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person("Alice", 30);
person.Greet();
person.Age = 31;
person.Greet();
// Using nested class
Person.Address address = new Person.Address
{
Street = "123 Main St",
City = "Springfield"
};
Console.WriteLine($"Address: {address.Street}, {address.City}");
}
}
}
Output
Hello, my name is Alice and I am 30 years old. Hello, my name is Alice and I am 31 years old. Address: 123 Main St, Springfield