Store instance data, define shared values, and build organized C# classes
In Object-Oriented Programming, fields and static members are essential for storing and managing data inside your classes. This topic helps you understand how to represent object-specific values, class-level state, and shared logic in clean, scalable ways.
๐น Fields: Storing Data Per Object
A field is a variable declared inside a class but outside any method. Fields store the state of an object and are typically marked as private to enforce encapsulation.
๐ง Example: Defining and Using a Field
public class Student
{
// Field (private by convention)
private string _name;
// Constructor
public Student(string name)
{
_name = name; // Field assignment
}
// Method using the field
public string Greet()
{
return $"Hello, my name is {_name}.";
}
}
Each Student instance has its own _name field, representing its personal data.
๐ช Default Field Initialization
You can also assign a default value directly:
private int _score = 0;
Default values are useful when an object might not always be constructed with full parameters.
๐ Properties vs. Fields
Fields are internal. To allow safe access from outside the class, you expose a property:
private int _age;
public int Age
{
get { return _age; }
set
{
if (value >= 0) _age = value;
}
}
โ
Use fields to store raw data
โ
Use properties to control how data is accessed or modified
๐ Static Members: Shared Across All Instances
A static member belongs to the class, not any specific object.
๐ฆ Static Field Example
public class User
{
private string _username;
public static int TotalUsers = 0;
public User(string username)
{
_username = username;
TotalUsers++;
}
public string Describe()
{
return $"{_username} is registered. Total users: {TotalUsers}";
}
}
โ
TotalUsers tracks a shared value, updated by every new User.
โ๏ธ Static Method Example
public static class Utilities
{
public static string Capitalize(string input)
{
return input.ToUpper();
}
}
You can call this method without creating an object:
string result = Utilities.Capitalize("hello");
๐ Constant Fields and readonly
Use const for fixed values:
public const double Pi = 3.14159;
Use readonly to set the value once, in constructor or declaration:
private readonly Guid _id = Guid.NewGuid();
๐ง When to Use What?
| Need | Use this |
|---|---|
| Store per-object state | Instance field |
| Safely expose or control access | Property |
| Share data across all instances | Static field |
| Provide global tools | Static method |
| Store fixed, compile-time value | Constant (const) |
๐งช Challenge Task
Create a class Book with:
- Private fields:
_title,_author - Public property:
Title - Static field:
TotalBooks - Constructor that increments
TotalBooks - Method
Describe()that returns title and author
๐ Summary
| Concept | Description | Example |
|---|---|---|
| Field | Stores object data | private string _name; |
| Property | Public accessor for a field | public int Age { get; set; } |
| Static Field | Shared across all instances | public static int Count; |
| Static Method | Utility function not tied to an object | public static string Tool() |
| Constant | Immutable value (compile-time) | public const string AppName |
| Readonly Field | Set only once (runtime or constructor) | private readonly Guid _id; |
โ Best Practices
- โ
Keep fields
privateand use properties for access - โ
Use
staticcarefully to avoid global state overuse - โ
Prefer
readonlyfor values set only once - โ
Use descriptive field names with
_camelCaseconvention - โ
Only use
publicfields if you have a specific design reason