SodiumFRP / sodium

Sodium - Functional Reactive Programming (FRP) Library for multiple languages
http://sodium.nz/
Other
848 stars 138 forks source link

C#: Maybe should be a value type? #92

Closed ziriax closed 8 years ago

ziriax commented 8 years ago

C# has value types, that can never be null. Shouldn't the C# version make use of that feature to implement the Maybe 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.

iCodeIT commented 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 ;-)

ziriax commented 8 years ago

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.

jam40jeff commented 8 years ago

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.

ziriax commented 8 years ago

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 ;-)