c# - where t : class generic constraint and const value declaration -
according c# specification in 10.4 constants
:
the type specified in constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, enum-type, or reference-type. each constant-expression must yield value of target type or of type can converted target type implicit conversion (§6.1).
why can't following:
public class genericclass<t> t : class { public const t val = null; }
that should possible, because:
where t : class
means,the type argument must reference type; applies class, interface, delegate, or array type
(from msdn)- it satisfies words specification: the possible value constants of reference-types other
string
null
.
any possible explanation?
possible explanation
consider how clr initializes static
members of generic classes or when invokes static constructors on generic types. normally, static initialization occurs when program first loaded; however, generic classes initialize static members first time instance of class created.
bear in mind generic class not single type; every single t
gets passed in type declaration creating new type.
now consider const
expression, has requirement evaluated @ compile-time. although t constrained class, , therefore can receive value null, variable val
not exist in memory until class has been created @ runtime.
for example, consider if const t val
valid. elsewhere in code use:
genericclass<string>.val genericclass<object>.val
edit
although both expressions have value null
, former of type string
, latter of type object
. in order compiler perform substitution, needs know type definitions of constants in question.
constraints may enforced @ compile-time, open generics not converted closed generics until runtime. therefore, genericclass<object>.val
cannot stored in compiler's local memory perform substitution because compiler not instantiate closed form of generic class, , not know type instantiate constant expression to.
Comments
Post a Comment