C# – How to Use Generic Constraints Without Class?

c++generics

is there a where clause for a generic that determines that T is of type primitive?

 void Method<T>(T val) where T : primitive

case:

have a functional language written in C that feeds on primitive unmanaged blitable types, or things that can be pushed into a primitive easily (eg. a date without hours/mins/seconds could be pushed to an int, etc.) The original plan was to utilise GPU. Not doing that though. C# is holding up well in its co-ordinator role so far. I tend to think of the schema's home as living in C#. This isn't strictly true, but the idea serves the project well.

I like OO, but when it comes to functional ideas, I'd like to constrain those thoughts to types that are supported in that domain. Interestingly, I'm still leaning on C# to help me stay structured and disciplined. I don't see that changing.


There are other reasons why getting more detailed with constraints would be a good thing for me.

btw: resharper suggested explicit interfaces which I tried for a while. I really liked this notation… and the constraints can live with the interface too. Nice. However, I came across Jon Skeet's warning on S/O about this messing up inheritance. So, back to a more labour intensive run-time AssertIsXYZ.

To take that a little further, where constraints to me are a step towards proof of correctness (old ideas, but still good ones). The typing system seems to enable some of this to be pushed to the compiler. Using the word "where" made think about a clause or phrase (like in SQL/LINQ). I'm not asking for it to be taken to the nth degree. The more work the compiler can do the better as far as I'm concerned.

Getting tactile with constraints helped me clarify some ideas. Got to give credit there… but it's a pity that I had to comment the constraints out afterwards.

Best Answer

I suspect that what you want based on your comments on Jon's answer is a way to constrain a type parameter to either blittable types or unmanaged types.

An "unmanaged type" is a type whose definition precludes any reference to memory tracked by the garbage collector; you can only make pointer types out of unmanaged types. Blittable types are those types which can be marshalled from managed to unmanaged code without any modification to their bits; they are a subset of the unmanaged types.

A number of people have told us that it would be quite handy to have a generic constraint that constrains a type parameter to be only an unmanaged type. We have experimented with prototypes of C# and the CLR that have this constraint, but have no plans at this time to actually put the feature into the product. If you can describe the scenario that is motivating the feature request, that would help us prioritize the feature against the hundreds of other features that are also possible.

Related Question