Reputation: 77
I have the following situation in C#:
class MyGenericClass<T>
{
public void do()
{
}
}
class SpecificFooImpl : MyGenericClass<Foo>
{
public void otherStuff()
{
}
}
Now I want to write a generic method which can return only MyGenericClass<T>
or specific implementations. I would write something like:
var v1 = GetMyClass<MyGenericClass<Foo>>();
var v2 = GetMyClass<MyGenericClass<Bar>>();
var v3 = GetMyClass<SpecificFooImpl>();
I could use the following signature but it have no constraints on the type:
public T GetMyClass<T>();
//I don't want to write
//var v4 = GetMyClass<AnyOtherTypesWhichNotExtendMyGenericClass>();
Is there any elegant mode to solve the problem?
Upvotes: 3
Views: 95
Reputation: 12163
Add a where : clause after the definition, then you can define what should be obeyed.
I've said it must be a class but you can add a base class or interface as a constraint.
class MyGenericClass<T> where T : class, IYourCommonInterface
{
public void do()
{
}
}
References:
See MSDN on constraints: http://msdn.microsoft.com/en-us/library/d5x73970.aspx
Upvotes: 2
Reputation: 41539
This gets a little tricky, as you can't leave the type constraint open - it has to be concrete.
So what you'd like to do is:
public T GetMyClass<T>() where T: MyGenericClass<>
However the closest you'd get is to include a second generic type that makes MyGenericClass
concrete:
public T GetMyClass<T,T2>() where T: MyGenericClass<T2>
However this makes the caller need to know too much about the implementation, especially where you're using SpecificFooImpl
.
Instead, consider using an interface to remove your inner generic type:
interface MyInterface
{
void Stuff();
}
class MyGenericClass<T> : MyInterface
{
public void Stuff()
{
}
}
Then you can have:
public T GetMyClass<T>() where T : MyInterface
Upvotes: 2