Hopeless Hopeless - 4 months ago 11
C# Question

Static or readonly modifier for field initialization

Have a class:

class MyClass
{
private static TimeSpan myField = TimeSpan.FromSeconds(5);

public void SomeMethod()
{
// usage of field
}
}


myField field initilizes inline. What modifier should I choose for it, static (as above) or readonly?

Answer

In C# previous to 6.0 you would implement a static readonly field wrapped by a static property.

BTW, In C# 6.0 and above, this can be simplified to:

class MyClass
{
   // A read-only property that can only be set with a property initializer
   // or in a static constructor
   private static TimeSpan MyProperty { get; } = TimeSpan.FromSeconds(5);

   public void SomeMethod()
   {
       // usage of field
   }
}

...which implements a backing static readonly field during compile-time.

Comments