In this article

Fields (C# Programming Guide)

In this article

A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.

A class or struct may have instance fields or static fields or both. Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object. By contrast, a static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visibly immediately to instances B and C if they access the field.

Generally, you should use fields only for variables that have private or protected accessibility. Data that your class exposes to client code should be provided through methods, properties and indexers. By using these constructs for indirect access to internal fields, you can guard against invalid input values. A private field that stores the data exposed by a public property is called a backing store or backing field.

Fields typically store the data that must be accessible to more than one class method and must be stored for longer than the lifetime of any single method. For example, a class that represents a calendar date might have three integer fields: one for the month, one for the day, and one for the year. Variables that are not used outside the scope of a single method should be declared as local variables within the method body itself.

Fields are declared in the class block by specifying the access level of the field, followed by the type of the field, followed by the name of the field. For example:

A field can be given an initial value by using the assignment operator when the field is declared. To automatically assign the day field to "Monday", for example, you would declare day as in the following example:

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration. For more information, see Using Constructors.

A field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time. For more information, see Constants.

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.