Fields

Field is a member of a class or struct and it can be both instance fields or static. Instance specific is from the instance type, however it should only be used for private or protected accessibility.

class
{
  string name;
  public int Age = 10;
}

Fields have modifiers:

  1. Static: static
  2. Access modifier: public, internal, private, protected
  3. Inheritance: new
  4. Unsafe code: unsafe
  5. Read-only: readonly
  6. Threading: volatile

Field Initialization

Initializing field is optional and an uninitialized has a default value of either 0,\0,null,false. They get executed before the constructors.

public int Age = 10;

Declaring multiple fields together

Same type fields can be declared in comma separated list

static readonly int a = 6, b = 7;

Read-only Fields

Read-only fields gets initialized during run-time and can only be assigned during initialization.

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            A a = new A(10);  
            Console.Read();  

        } 
    }
    
    class A  
    {  
        public readonly int m;  
        public static readonly int n;  
        public A(int x)  
        {  
            m = x;  
            Console.WriteLine("" + m);  
        }  
        static A()  
        {  
            n = 100;  
            Console.WriteLine("" + n);  
        }  
    }
}

Datetime example

Can initialize readonly field in constructor but you cannot reassign later. Benefit – no one else can change the code from your team.

// you inline initialization also
readonly DateTime _startup = DateTime.Now;

Leave a Reply

Your email address will not be published. Required fields are marked *