Value / primitive type constraints on generics

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Is it possible to constrain a generic to be a value or primitive type?

(Any kludges/workarounds welcome if the immediate answer is no....)
 
Dave,

Yes, it is. You would do this:

public class MyClass<T> where T : struct

Hope this helps.
 
Michael,

What I think he meant to ask was will the constraint using "struct"
allow an int to be passed for the type parameter T.
 
Michael Bray said:
What would be the point of using Generics if you are specifying the exact
type?

On the surface I don't exactly see how an int is equivalent to a struct,
except in the broad sense that they are both value types. Frankly, I'm
surprised that that works.

Sorry if I seem lazy but I'm not in a position to test out an example on my
own at this moment.

-- Alan
 
What I think he meant to ask was will the constraint using "struct"
allow an int to be passed for the type parameter T.

Yeah I realized that after I saw your response. :) That's why I'm eating
lunch at 4:30.

-mdb
 
Sadly, you can't constrain a generic to be an Enum.

public class MyClass<T> where T : Enum

:(
 
Alan Pretre said:
On the surface I don't exactly see how an int is equivalent to a struct,
except in the broad sense that they are both value types. Frankly, I'm
surprised that that works.

In what way is it *not* a struct? Heck, if you look in MSDN it's even
documented with a struct declaration:

[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct Int32 : IComparable, IFormattable, IConvertible,
IComparable<int>, IEquatable<int>

Now, I agree that it's different in terms of there being built-in
support for it in the CLR, *and* in terms of it being in some sense
"atomic" - but it works like a perfectly normal struct in general.
 
Hi ,

I just wanted to check how things are going. If there is any question,
please feel free to join the community and we are here to support you at
your convenience. Thanks again and have a nice day!

Best Regards,

Terry Fei[MSFT]
Microsoft Community Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 
Back
Top