How do I add general restrictions?
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 that can only return MyGenericClass 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 has no type restrictions:
public T GetMyClass<T>();
//I don't want to write
//var v4 = GetMyClass<AnyOtherTypesWhichNotExtendMyGenericClass>();
Is there an elegant way to solve the problem?
source to share
Add where clause: after definition, then you can define what should be done.
I said it should be a class, but you can add a base class or an interface as a constraint.
class MyGenericClass<T> where T : class, IYourCommonInterface
{
public void do()
{
}
}
Links :
See MSDN for restrictions: http://msdn.microsoft.com/en-us/library/d5x73970.aspx
source to share
This is a bit tricky as you cannot leave the type constraint open - it must be specific.
So what do you want to do:
public T GetMyClass<T>() where T: MyGenericClass<>
However, the closest to you would be an inclusion of the second type, which makes it MyGenericClass
specific:
public T GetMyClass<T,T2>() where T: MyGenericClass<T2>
However, this makes the caller know too much about the implementation, especially if you are using SpecificFooImpl
.
Instead, consider using an interface to remove the inner type:
interface MyInterface
{
void Stuff();
}
class MyGenericClass<T> : MyInterface
{
public void Stuff()
{
}
}
Then you can:
public T GetMyClass<T>() where T : MyInterface
source to share