Closed ziriax closed 8 years ago
Structs are not slow in C# if they are not too big and if it solves a problem without introducing new ones, then I would say go for it ;-)
Yes I meant that C# structs are much slower than they could have been ;-) I can't find the article back, I think Joe Duffy wrote about it.
But anyway the semantics of a value-type seem more appropriate for a Maybe
type.
I made Maybe a reference type so it could be exposed via an interface and thus be covariant as a normal value would be (IMaybe<string>
is assignable to IMaybe<object>
, etc.) I know this is technically possible with a strict, but the boxing and unboxing would negate any advantages of using the structure (and the fact that user code types the variables as the interface wouldn't provide any safety against values being null if left uninitialized). Using a struct isn't a bad idea, but we would lose covariance, and I'm not sure if it's worth it.
For what it's worth, the FSharpOption type is also a class.
Maybe one day we'll get non-nullable reference types in C# (or better yet we'll all move to F#! :) ). Until then, I just use Code Contracts on my projects to help ensure that Maybe are not null.
I see, thanks for clarifying this.
F# does not allow null values of the FSharpOption type, so that helps :-)
Oh yes, C# must get non-nullable reference types, otherwise the Swift guys will become much more productive than us ;-)
C# has value types, that can never be
null
. Shouldn't the C# version make use of that feature to implement theMaybe
type? Because right now,IMaybe
can again be null. Making this a struct eliminates this class of bugs. I know that structs are rather slow in C#, but that should not be relevant here I guess.