3

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?

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

How can I write the where clause? I cannot find a way to achieve it!
Copy what I have, then define an interface or another base class as a constraint
2

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

1 Comment

All of the desired usages will work (eg var v3 = GetMyClass<SpecificFooImpl>();) since they all derive from MyGenericClass<T> which now implements MyInterface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.