views:

117

answers:

3

This may be a bit of an abstract question, so apologies in advance.

I am looking into generics in .NET, and was wondering about the where T : struct constraint.

I understand that this allows you to restrict the type used to be a value type. My question is, without any type constraint, you can do a limited number of operations on T.

Do you gain the ability to use any additional operations when you specify where T : struct, or is the only value in restricting the types you can pass in?

Edit

Some interesting answers so far, thanks. I guess the question I am actually asking is that if i were to write, (in a discussion about how to use generics),

"Now that you have constrained the type argument to value types, you can also do _________ on/with objects of that type"

Is there anything to put in that blank? I can think of things for the other constraints, but not this one.

+4  A: 

All that T : struct gains you is an implicit new() constructor, and a few obvious things involving null. Perhaps more importantly, callers can't use classes, interfaces or Nullable<T>.

What types of operations are you after? For operators, try dynamic in 4.0, or MiscUtil in 3.5

Marc Gravell
Thanks. Edited my question to be a bit clearer.
Fiona Holder
A: 

No, you don't gain any operations on T by specifying the where T: struct generic type constraint. You constrain your callers to only specify value types (except Nullable<T> value types, which are not allowed).

Håvard S
Except the `new T()` operation. And you *lose* the ability to compare `T` to `null`.
Marc Gravell
Losing is not gaining, and `new T()` is really not a gain, since you have `default(T)` yielding the same result.
Håvard S
True, true (on the `new T()`===`default(T)`). I could argue that having the compiler spot an obvious brain-dead test is gaining, but I kinda have to agree with you ;-p
Marc Gravell
+2  A: 

The only thing that you gain relative to other possible sets of constraints is the ability to work with values of type Nullable<T> (which is why T: struct prohibits caller from passing Nullable<T> as a type parameter - it can't be nested).

Pavel Minaev
This is just a special case of "With the constraint T : struct, you can use T as the actual parameter for any other generic type requiring T : struct".
Ben Voigt