How to declare a class instance as a constant in C#?

Solution 1:

Using readonly instead of const can be initialized and not modified after that. Is that what you're looking for?

Code example:

static class MyStaticClass
{
    static readonly TimeSpan theTime;

    static MyStaticClass()
    {
        theTime = new TimeSpan(13, 0, 0);
    }
}

Solution 2:

Constants have to be compile time constant, and the compiler can't evaluate your constructor at compile time. Use readonly and a static constructor.

static class MyStaticClass
{
  static MyStaticClass()
  {
     theTime = new TimeSpan(13, 0, 0);
  }

  public static readonly TimeSpan theTime;
  public static bool IsTooLate(DateTime dt)
  {
    return dt.TimeOfDay >= theTime;
  }
}

In general I prefer to initialise in the constructor rather than by direct assignment as you have control over the order of initialisation.

Solution 3:

C#'s const does not have the same meaning as C++'s const. In C#, const is used to essentially define aliases to literals (and can therefore only be initialized with literals). readonly is closer to what you want, but keep in mind that it only affects the assignment operator (the object isn't really constant unless its class has immutable semantics).