A field is a variable that is a member of a class or struct.
For example:
class Person {
string name;
public int Age = 10;
}
Fields allow the following modifiers:
Description | Modifier |
---|---|
Static modifier | static |
Access modifiers | public internal private protected |
Inheritance modifier | new |
Unsafe code modifier | unsafe |
Read-only modifier | readonly |
Threading modifier | volatile |
The readonly modifier prevents a field from being modified after construction.
A read-only field can be assigned only in its declaration or within constructor.
Field initialization is optional.
An uninitialized field has a default value.
Field initializers run before constructors.
The following code initializes the Age variable to 10.
class Person{
public int Age = 10;
}
We may declare multiple fields of the same type in a comma-separated list.
For example:
class Bug{
static readonly int legs = 8, eyes = 2;
}