Re: Static property of type parameter - is this a CLR or C# limitation?

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



"Ole Nielsby" <ole.nielsby@xxxxxxxxxxxx> wrote:


Barry Kelly <barry.j.kelly@xxxxxxxxx> wrote:

[...some insights in generics compilation...]

So, I would say it is a current architectural limitation of the CLR.

Thanks for a detailed explanation.

Belay that order! Your post got me thinking, and I realised that the
same "problem" of passing the generic argument would occur for instance
methods. So I investigated further with ILASM. I patched up the IL that
referred to an instance property to refer to a static property instead.
It compiled correctly with ilasm, and ran correctly.

I then ran it through Reflector to see what it thought of the IL. Then I
saw the error of my ways...

You can indeed access a static property of a type argument, via the more
prosaic route of using the same type as specified in the constraint:

---8<---
class A<T>
{
public static T StaticValue
{
get { return default(T); }
}
}

class B<T,U>
where T : A<U>
{
public B()
{
}

public U Value
{
get { return A<U>.StaticValue; }
}
}
--->8---

Don't forget that the storage for a static field is the shared for all
its descendants - there isn't a unique copy of statics per descendant
class, so the limitation on directly accessing T isn't actually a
limitation at all.

Sorry for overcomplicating matters...

HTH,

-- Barry
.