Extending the .NET type system so the compiler enforces semantic meaning of primitive values in cert

Posted by Drew Noakes on Stack Overflow See other posts from Stack Overflow or by Drew Noakes
Published on 2010-05-31T19:03:09Z Indexed on 2010/05/31 19:13 UTC
Read the original article Hit count: 255

Filed under:
|
|
|

I'm working with geometry a bit at the moment and am converting a lot between degrees and radians. Unfortunately, both of these are represented by double, so there's compile time warning/error if I try to pass a value in degrees where radians are expected.

I believe F# has a compile-time solution for this (called units of measure.) I'd like to do something similar in C#.

As another example, imagine a SQL library that accepts various query parameters as strings. It'd be good to have a way of enforcing that only clean strings were allowed to be passed in at runtime, and the only way to get a clean string was to pass through some SQL injection attack preventing logic.

The obvious solution is to wrap the double/string/whatever in a new type to give it the type information the compiler needs. I'm curious if anyone has an alternative solution. If you do think wrapping is the only/best way, then please go into some of the downsides of the pattern (and any upsides I haven't mentioned too.) I'm especially concerned about the performance of abstracted primitive numeric types on my calculations at runtime.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET