Vivian River
Vivian River

Reputation: 32400

C#: How to design a generic class so that the type parameter must inherit a certain class?

I've written a class that looks like this:

public class MyClass<T>
{
    public void doSomething()
    {
       T.somethingSpecial;
    }
}

This code doesn't compile because the compiler has no idea what T is. I would like to constrain T so that it must inherit a certain class that defines somethingSpecial. Bonus points if you can tell me how to do the same thing by contraining T so that it must implement a certain interface.

Upvotes: 3

Views: 1430

Answers (6)

TomTom
TomTom

Reputation: 62157

Read the documentation. Generic Constraint.

class MyClass<T> where T : someinterfaceorbaseclassthatTmustinherit

Upvotes: 1

Samuel Slade
Samuel Slade

Reputation: 8623

public interface ISomeInterface
{
    void DoSomething();
}

public class MyClass<T> where T : ISomeInterface
{
    public void doSomething()
    {
       T.DoSomething();
    }
}

The where keyword allows you to specify constraints on the given generic type. You could swap out the interface for a class.

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245479

What you want is a generic constraint:

public class MyClass<T> where T : SomeParentClass

Upvotes: 4

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41767

You need a Generic Constraint:

public class MyClass<T> where T : ISomeInterface
{
  public void doSomething()
  {
    instanceOfT.somethingSpecial();
  }
}

Upvotes: 1

Ondrej Tucny
Ondrej Tucny

Reputation: 27974

Use the following type parameter constraint in the class declaration:

public class MyClass<T> where T : MyBaseClass

You can read more about type parameter contraints for example here at MSDN.

Upvotes: 4

Austin Salonen
Austin Salonen

Reputation: 50235

public class MyClass<T> where T: IAmSomethingSpecial

It's called Constraints on Type Parameters.

Upvotes: 15

Related Questions