Benjamin Good
Benjamin Good

Reputation: 201

How do I use a generic type within a generic class declaration?

The following code...

class Repository<T> where T : Func<TIn, TOut>
{
//...
}

causes VS to complain that "the type or namespace name 'TIn'/'TOut' could not be found."

Is there any way to do this?

Upvotes: 0

Views: 114

Answers (4)

Kenneth
Kenneth

Reputation: 28747

Since you already know the type you want, there's no need to put a constraint on it. I think what you want is this:

class Repository<TIn, TOut>
{
    public void someMethod(Func<TIn, TOut> func)
    {

    }
}

Upvotes: 1

James
James

Reputation: 82136

If Func itself was a generic class, then yes you could via:

class Repository<T, TIn, TOut> where T: Func<TIn, TOut> 

However, you couldn't do this with Func as it can only be constrained by an interface/non-sealed class or a type parameter.

As an alternative, you could pass the Func in as a constructor argument and it would work i.e.

class Repository<TIn, TOut>
{
    public Repository(Func<TIn, TOut> func)
    {
        ...
    }
}

Not really sure if that would give you what you're after though.

Upvotes: 3

Matthew Watson
Matthew Watson

Reputation: 109822

You can't constrain a type T to Func because you can only constrain types to interfaces, non-sealed classes or type parameters.

If you could do it, it would look like this:

class Repository<T, TIn, Tout> where T: Func<TIn, TOut>
{
    //...
}

But you're not allowed to constrain to Func<>, so the whole thing is doomed.

The error message from the compiler is:

Error 1 'System.Func' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.

Upvotes: 0

Agustin Meriles
Agustin Meriles

Reputation: 4854

You must specify the "inputs" for TIn and TOut in the definition of your class, otherwise, the compiler doesn't figure out from where took that

class Repository<T, TIn, TOut> where T : Func<TIn, TOut>
{
    //...
}

Upvotes: 0

Related Questions