Understanding Fields, Static Members, and Class-Level Logic in C#

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?

NeedUse this
Store per-object stateInstance field
Safely expose or control accessProperty
Share data across all instancesStatic field
Provide global toolsStatic method
Store fixed, compile-time valueConstant (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

ConceptDescriptionExample
FieldStores object dataprivate string _name;
PropertyPublic accessor for a fieldpublic int Age { get; set; }
Static FieldShared across all instancespublic static int Count;
Static MethodUtility function not tied to an objectpublic static string Tool()
ConstantImmutable value (compile-time)public const string AppName
Readonly FieldSet only once (runtime or constructor)private readonly Guid _id;

โœ… Best Practices

  • โœ… Keep fields private and use properties for access
  • โœ… Use static carefully to avoid global state overuse
  • โœ… Prefer readonly for values set only once
  • โœ… Use descriptive field names with _camelCase convention
  • โœ… Only use public fields if you have a specific design reason