Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# How to put a constraint on a generic Func argument that is within a method signature

Tags:

c#

generics

public void Test<TFeature>(Func<TController, ViewResult> controllerAction)                                          
            where TController : IController
            where TFeature : ISecurityFeature
        {
            ...
        }

I'm getting the error, Test does not define type parameter TController. How can I put a constraint on TController?

like image 567
contactmatt Avatar asked Dec 28 '22 06:12

contactmatt


2 Answers

Unless you are defining it inside SomeClass<TController> (in which case you need to put constraint next to class SomeClass<TController>), you need to make TController a generic argument of your function, i.e.:

public void Test<TFeature, TController>(Func<TController, ViewResult> controllerAction)                                          
            where TController : IController
            where TFeature : ISecurityFeature
        {
            ...
        }
like image 97
Krizz Avatar answered Jan 18 '23 23:01

Krizz


You need to add the TController as a generic parameter too

public void Test<TFeature, TController>(Func<TController, ViewResult> controllerAction)                                          
        where TController : IController
        where TFeature : ISecurityFeature
    {
        ...
    }
like image 32
Trevor Pilley Avatar answered Jan 19 '23 00:01

Trevor Pilley