CSharp/C# Tutorial - C# Fields






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:

DescriptionModifier
Static modifierstatic
Access modifierspublic internal private protected
Inheritance modifiernew
Unsafe code modifierunsafe
Read-only modifierreadonly
Threading modifiervolatile




The readonly modifier

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

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; 
}

Declaring multiple fields together

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; 
}