Search code examples
c#genericsenumsvalue-type

How to declare a const field of a generic value type provided as generic argument


I'm trying to define a generic class that accept as argument a value type (actually it will be an enum) and initialize a const field with it's default type.

I want something like:

public abstract class GenericClass<ValueType> 
    where ValueType: struct, IConvertible
{
  public const ValueType val = default(ValueType);
}

Unfortunately the compiler complaints (I'm using Mono but I think it's the same on .NET). The error is the following:

error CS1959: Type parameter `ValueType' cannot be declared const

What's my error?


Solution

  • Type parameter is not allowed for constant type.

    Because a struct cannot be made const (from C# specification 10.4 Constants)

    The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type.

    A kind of workaround to this limitation is to declare it as static readonly.

    public static readonly ValueType val = default(ValueType);