Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

According to its definition in MSDN: a constant expression is an expression that can be evaluated completely at compiling time.

According to this SO answer, that references this interview:

Anders Hejlsberg: [...] In the CLR [Common Language Runtime], when you compile List, or any other generic type, it compiles down to IL [Intermediate Language] and metadata just like any normal type. The IL and metadata contains additional information that knows there's a type parameter, of course, but in principle, a generic type compiles just the way that any other type would compile. At runtime, when your application makes its first reference to List, the system looks to see if anyone already asked for List. If not, it feeds into the JIT the IL and metadata for List and the type argument int. The JITer, in the process of JITing the IL, also substitutes the type parameter.

Thus, because the type is not defined at compiling, the default value cannot be get until runtime.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top