Reputation: 4863
I want to access to static fields of a type, which is a class, introduced in a generic function. But compiler always gives me this error
'T' is a 'type parameter', which is not valid in the given context
here is the code.
public class A
{
public static int Num = 1;
public int GetClassNum<T>() where T : A
{
//return T.Num;
//return default(T).Num;
//return what???
}
}
public class B : A
{
public static int Num = 2;
}
public class C : A
{
public static int Num = 3;
}
I suspect that this has something to do with the fact that interfaces are generally used to filter the typename in a generic function. or must it be always? In this case there should not be a static field. Is there any way I can achieve?
Upvotes: 4
Views: 871
Reputation: 16032
Static fields belong to type, not instance of the type. You cannot refer to the static elements of the type parameter because they are not inherited.
Make Num not static property:
public class A
{
public virtual int Num
{
get { return 1; }
}
public int GetClassNum<T>(T instance) where T : A
{
return instance.Num;
}
}
public class B : A
{
public override int Num
{
get { return 2; }
}
}
public class C : A
{
public override int Num
{
get { return 3; }
}
}
Upvotes: 1
Reputation: 65877
What you are doing is wrong, you are trying to access a type, not an instance.
So how to resolve this,
public class A
{
public static int Num = 1;
public int GetClassNum<T>(T inn) where T : A
{
inn.Num //really
}
}
wait, wait... You cant do this too. Because Num is static and what we have passed (T inn) is a object reference(Only a class can access static fields, not objects).Then how can we make this work. One way is to make T as a static type, so
public static class A
{
public static int Num = 1;
public int GetClassNum<T>(T inn) where T : A // Error here
{
inn. /// no Num
}
}
wait, you cant do this too. Because you cannot use static instances as generic constraint because static is sealed itself.
So How to access Num, change Num to object instance or refer Preets answer for other option.
Upvotes: 1
Reputation: 65506
try this:
public class A
{
private static int _num = 1;
public virtual int Num { get { return _num; } set { _num = value; } }
public int GetClassNum<T>(T input) where T : A
{
return input.Num;
}
}
Then override Num in the derived classes
Upvotes: 1