Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type in generic constraint

Tags:

c#

generics

I want to be able to specify something like this:

public abstract class ColumnFilter<TCell, TFilterControl> : ColumnFilter
    where TFilterControl : FilterControl<>, new()
    where TCell : IView, new()
{
}

Class FilterControl<> is a base class. I can not know what will be the generic argument for FilterControl<>.

like image 524
b0bi Avatar asked Jun 25 '14 13:06

b0bi


People also ask

What is generic type?

A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept.

Can generic classes be constrained?

Declaring those constraints means you can use the operations and method calls of the constraining type. If your generic class or method uses any operation on the generic members beyond simple assignment or calling any methods not supported by System. Object, you'll apply constraints to the type parameter.

What does the generic constraint of type interface do?

Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.


2 Answers

You can't use unbound generic types in type constraints. You'd have to add a third type parameter, like this:

public abstract class ColumnFilter<TCell, TFilterControl, TFilterControlType> : ColumnFilter
    where TFilterControl : FilterControl<TFilterControlType>, new()
    where TCell : IView, new()
{
}

Or create a non-generic base type of FilterControl:

public FilterControl { }
public FilterControl<T> : FilterControl { }

public abstract class ColumnFilter<TCell, TFilterControl> : ColumnFilter
    where TFilterControl : FilterControl, new()
    where TCell : IView, new()
{
}

You can also make the base type abstract with internal constructors if you want to force consumers to use your generic derived type.

like image 103
p.s.w.g Avatar answered Oct 16 '22 05:10

p.s.w.g


ColumnFilter will have to be told what that type will be.

Add a third generic type parameter, like so:

public abstract class ColumnFilter<TCell, TFilterControl, TFilter> : ColumnFilter
    where TFilterControl : FilterControl<TFilter>, new()
    where TCell : IView, new()
{
}
like image 33
dcastro Avatar answered Oct 16 '22 04:10

dcastro