संपादित करें

Fields and constants

Tip

This article is part of the Fundamentals section for developers who already know at least one programming language and are learning C#. If you're new to programming, start with the Get started tutorials first.

Coming from another language? If you used Java fields and static final declarations, you recognize per-object state and named fixed values. In C#, choose const for a compile-time constant or readonly for a field you assign during initialization.

A field is a variable declared in a type. A field stores state associated with an instance of the type or the type itself. See the class reference for member declaration syntax. Use instance fields for each object's state and static fields for state shared by the type. For example, the counter uses one of each:

public class VisitCounter
{
    private int count;
    private static int total;

    public void AddVisit()
    {
        count++;
        total++;
    }

    public int GetCount() => count;

    public static int GetTotal() => total;

    public static int GetTotalExcluding(VisitCounter counter) =>
        total - counter.count;
}

A separate copy of count exists in each VisitCounter object. The static field total is shared by all instances of this class.

Use private fields for state that your class manages. Expose operations through methods or values through properties. In the counter, AddVisit keeps the two counts in sync.

Initialize fields and limit reassignment with readonly

To give a field a starting value, use a field initializer, an expression that supplies an initial value in the declaration:

public class Reminder
{
    private string text = "Take a break";

    public string GetText() => text;
}

Each new Reminder starts with its own "Take a break" text. If you omit an explicit initializer, a field starts with its type's default value, such as 0 for int, false for bool, or null for a reference type.

When you need caller-supplied values or need to coordinate initialization across fields, use a constructor. A constructor is a member that initializes a new object. See Constructors for examples.

To preserve a field's value after runtime initialization, declare a readonly field using the readonly keyword. You can assign an instance readonly field at its declaration or in an instance constructor of its containing type. Its value needn't be known at compile time. See the readonly reference for the precise rules.

For example, you can preserve the time when each session object was created:

public class Session
{
    private readonly DateTime startedAt = DateTime.UtcNow;

    public DateTime GetStartTime() => startedAt;
}

Each Session gets its own startedAt value. After initialization, you can read the field, but a method can't assign a different value to it.

For a reference-valued field, readonly prevents replacement of the reference, not changes to the referenced object. See the shallow-copy example for record classes.

Use named constants for common values

Give fixed values meaningful names so you can express their purpose instead of repeating unexplained literals, often called "magic values", in your code. For example, SecondsPerMinute tells a reader why you use 60 in a time calculation.

A constant is a named value that the compiler can determine at compile time. Declare it with const and supply its value in the declaration:

public static class TimeUnits
{
    public const int SecondsPerMinute = 60;
    public const int SecondsPerHour = 60 * SecondsPerMinute;
}

Use the type name and constant name to access a constant declared in another type. The compiler substitutes the constant value where your code uses it:

Console.WriteLine(TimeUnits.SecondsPerMinute); // => 60
Console.WriteLine(TimeUnits.SecondsPerHour); // => 3600

A member constant such as SecondsPerMinute is implicitly static: it belongs to the type. Adding static would be redundant, and C# doesn't allow you to combine static with const.

You can declare constants of numeric types, bool, char, string, and enum types. A reference-type constant other than a string can only hold null; you can't create a constant array or object with new. For related named integral values, see Enumerations. C# #define defines conditional-compilation symbols, not constant values.

Important

A compiled caller contains the value of a constant from a referenced assembly. If that assembly changes the constant, recompile the caller to use the new value. For compatibility details, see the existing constants guide.

Use static readonly for a runtime constant

When you need one fixed value for the type that can't be a compile-time constant, use a static readonly field. For example, give reminders a shared interval:

public static class ReminderSettings
{
    public static readonly TimeSpan Interval = TimeSpan.FromMinutes(15);
}

A TimeSpan represents a time interval. The call to TimeSpan.FromMinutes(15) creates the value at run time. A TimeSpan value can't be declared with const, so static readonly gives this shared interval a name and prevents reassignment after initialization.

You can assign a static readonly field in its declaration, as shown, or in a static constructor, a member the runtime calls automatically to initialize a type. Use a static constructor when initialization needs multiple statements. See Static constructors for details.

Further reading