Compartir a través de


Fields (C# Programming Guide)

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:

public class CalendarEntry
{
    // private field 
    private DateTime date;

    // public field (Generally not recommended.) 
    public string day;

    // Public property exposes date field safely. 
    public DateTime Date 
    {
        get 
        {
            return date;
        }
        set 
        {
            // Set some reasonable boundaries for likely birth dates. 
            if (value.Year > 1900 && value.Year <= DateTime.Today.Year)
            {
                date = value;
            }
            else 
                throw new ArgumentOutOfRangeException();
        }

    }

    // Public method also exposes date field safely. 
    // Example call: birthday.SetDate("1975, 6, 30");
    public void SetDate(string dateString)
    {
        DateTime dt = Convert.ToDateTime(dateString);

        // Set some reasonable boundaries for likely birth dates. 
        if (dt.Year > 1900 && dt.Year <= DateTime.Today.Year)
        {
            date = dt;
        }
        else 
            throw new ArgumentOutOfRangeException();
    }

    public TimeSpan GetTimeSpan(string dateString)
    {
        DateTime dt = Convert.ToDateTime(dateString);

        if (dt != null && dt.Ticks < date.Ticks)
        {
            return date - dt;
        }
        else 
            throw new ArgumentOutOfRangeException();  

    }
}

To access a field in an object, add a period after the object name, followed by the name of the field, as in objectname.fieldname. For example:

CalendarEntry birthday = new CalendarEntry();
birthday.day = "Saturday";

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:

public class CalendarDateWithInitialization
{
    public string day = "Monday";
    //...
}

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 (C# Programming Guide).

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 (C# Programming Guide).

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 (C# Programming Guide).

A field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. A staticreadonly 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# Programming Guide).

C# Language Specification

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

See Also

Reference

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