Closed solvingj closed 3 months ago
You are right, Maybe
in the current implementation is for reference types only. For Enums, I'd recommend using the built-in Nullable<>
type. For example:
MyEnum? myEnum = MyEnum.SomeValue;
The compiler automatically transforms ?
into Nullable<MyEnum>
here.
Indeed, why not just using Nullable<>
instead of Maybe<>
in all your code?
@StefH because Nullable<>
is restricted to only Value Types (structs).
Which types are not supported?
Could you please elaborate?
@StefH reference types, such as classes for example.
Same here, I often find myself stuck with patterns like:
MaybeVar.Select(v => v.IntProp).Unwrap(42);
(where MaybeVar is a Maybe<T>
and IntProp
is an int
property of T
) failing because of that limitation.
So I have to go through if(MaybeVar.HasValue) ...
that doesn't feel very 'Monadic'...
The duality betwwen Maybe<RefType>
and Nullable<ValType>
doesn't seem to allow for fluent constructs. Or did I missed something?
@manuel-ornato Great point. My initial inclination was that having two competing types (Nullable<>
and Maybe<>
) would bring confusion. But now that I think more about it, it makes sense to remove this limitation in order to enable fluent syntax with .NET value types.
I'll try to remove it soon and republish the package. @solvingJ , feel free to send a pull request too if you will.
I think this makes a lot of sense. I'll give it a try ASAP.
Maybe
is now capable of holding and correctly handling enumeration types and other structure types, so I think this issue could be closed.
I think I just determined that Maybe can't be used to hold enum's because it can currently only hold reference types, is this correct?
If so, I think it's because you've constrained T to "class" specifically.
public struct Maybe<T> : IEquatable<Maybe<T>> where T : class
Can you think of any easy way to achieve an enum type in a Maybe?
For the record, I was trying to implement text parsing adapters for enums and other primitive types into Maybe's. The goal was similar to what was achieved here:
https://github.com/louthy/language-ext
If you scroll down, you can see how they replaced TryParse with parseInt that returns an option.
Interestingly, they did not do am implementation for parseEnum, but in theory they could have.