Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining bounded generic type parameter in C#

In Java, it is possible to bind the type parameter of a generic type. It can be done like this:

class A<T extends B> {
    ...
}

So, the type parameter for this generic class of A should be B or a subclass of B.

I wonder if C# has a similar feature. I appreciate if somebody let me know.

Thanks

like image 874
Morteza Avatar asked Mar 29 '12 20:03

Morteza


People also ask

What are bounded type parameters in generic?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.

What is the syntax for bounded type parameters?

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

What is a generic type parameter?

Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

Is it possible to declared a multiple bounded type parameter?

A type parameter can have multiple bounds.


2 Answers

The same in C# is:

class A<T> where T : B
{

}

Also see "Constraints on Type Parameters" (msdn) for a great overview of constraints in general.

like image 76
BrokenGlass Avatar answered Oct 06 '22 00:10

BrokenGlass


Very similar:

public class A<T> where T : B
{
    // ...
}

This can be used to constrain T to be a sub-class or implementation of B (if B is an interface).

In addition, you can constrain T to be reference type, value type, or to require a default constructor:

where T : class     // T must be a reference type
where T : struct    // T must be a value type
where T : new()     // T must have a default constructor
like image 37
James Michael Hare Avatar answered Oct 06 '22 00:10

James Michael Hare