Defining a limited type type parameter in C #

In java, you can bind a type parameter to a generic type. This can be done as follows:

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

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

I wonder if C # has a similar function. I appreciate if anyone informs me.

Thanks,

+6
source share
4 answers

Same thing in C #:

 class A<T> where T : B { } 

Also see "Type Parameter Constraints" (msdn) for a large overview of constraints in general.

+16
source

Is very similar:

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

This can be used to restrict T to be a subclass or implementation of B (if B is an interface).

Alternatively, you can restrict T to a reference type, a value type, or 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 
+9
source

Of course you can:

 class A<T> where T: B { // ... } 
+3
source

Yes, you can do this, it is called type constraints. Here is an article that explains how:

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

+2
source

Source: https://habr.com/ru/post/911978/


All Articles