Defining bounded generic type parameter in C#
Asked Answered
D

4

12

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

Decrepitude answered 29/3, 2012 at 20:44 Comment(1)
class A<T> where T : B {...} I think. It's been awhile.Fourdimensional
S
23

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.

Scrim answered 29/3, 2012 at 20:45 Comment(1)
Beat me by a few seconds while I was finishing mine, +1 for the MSDN link.Hexavalent
H
12

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
Hexavalent answered 29/3, 2012 at 20:45 Comment(0)
M
3

Of course you can:

class A<T> where T: B
{
    // ...
}
Monoplegia answered 29/3, 2012 at 20:45 Comment(0)
R
3

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

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

Rafa answered 29/3, 2012 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.