Fields (C# Programming Guide) 

This topic describes fields, which are objects or values contained in a class or struct. Fields allow classes and structures to encapsulate data.

For simplicity, these examples use fields that are public, but this is not recommended in practice. Fields should generally be private. Access to fields by external classes should be indirect, by means of methods, properties, or indexers. For more information, see Methods, Properties and Indexers.

Fields

Fields store the data a class needs to fulfill its design. For example, a class representing a calendar date might have three integer fields: one for the month, one for the day, and one for the year. Fields are declared within 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:

public class CalendarDate
{
    public int month;
    public int day;
    public int year;
}

Accessing a field in an object is done by adding a period after the object name, followed by the name of the field, as in objectname.fieldname. For example:

CalendarDate birthday = new CalendarDate();
birthday.month = 7;

A field can be given an initial value by using the assignment operator when the field is declared. To automatically assign the month field to 7, for example, you would declare month like this:

public class CalendarDateWithInitialization
{
    public int month = 7;
    //...
}

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

Note

A field initializer cannot refer to other instance fields.

Fields can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the fields. For more information, see Access Modifiers.

A field can optionally be declared static. This makes the field available to callers at any time, even if no instance of the class exists. For more information, see Static Classes and Static Class Members.

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 following sections in the C# Language Specification:

  • 1.6.4 Fields

  • 10.4 Fields

See Also

Reference

Objects, Classes and Structs (C# Programming Guide)
Using Constructors (C# Programming Guide)
Inheritance (C# Programming Guide)
Access Modifiers (C# Programming Guide)
Abstract and Sealed Classes and Class Members (C# Programming Guide)

Concepts

C# Programming Guide