Lim Lim - 2 months ago 15
C# Question

in C# Generics this is impossible?

class Bar
{
static public Bar Instance { get { return null; /*return instance*/ } }
}

private void Foo<T>() where T : Bar
{
T getInstace = T.Instance;
}


this is error, but need get Instance.

this have a solution?

thank

++

class Bar<T>
{
static public T Instance { get { return default(T); /*return instance*/ } }
}

class BarChild : Bar<BarChild>
{
public void Func(){}
}

private T Foo<T>() where T : Bar<T>
{
return T.Instance;
}

private void Example()
{
Foo<BarChild>().Func();
}


I would like to be doing this you know.
but, "T.Instance" is error..

Answer

I think this boils down to a fundamental misunderstanding of the static keyword. It is NOT a mechanism for sharing members across instances, it is a way to inform the compiler that it can allocate the member statically, i.e. without regard to the dynamic behaviour of the program at run-time.

Note that you cannot make a static member virtual, which means that you can't override it in a subclass. Since subclassing is a static process, you can reference static members of a parent class as if they were inherited, because the compiler can work out where the member is defined.

Even if what you're describing were syntactically legal, there would be no way for T.Instance to refer to anything other than Bar.Instance.