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,