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

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.


From this link:

Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null.

If you want to create an object, it must be done so as static readonly:

static class MyStaticClass
{
  public static readonly TimeSpan theTime = new TimeSpan(13, 0, 0);
  public static bool IsTooLate(DateTime dt)
  {
    return dt.TimeOfDay >= theTime;
  }
}

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).


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

Tags:

C#

.Net

Constants