CSharpFunctionalExtensions icon indicating copy to clipboard operation
CSharpFunctionalExtensions copied to clipboard

Type-constraint on Maybe

Open linkdotnet opened this issue 6 years ago • 4 comments

Currently the implementation of Maybe<T> checks for null to determine if it has an value. This makes obvious sense if you have reference-type but not for value-types. This seems a bit inconsistent to me. I would propose one out of two options:

  1. Make a reference-type constraint on the type-generic of Maybe: public struct Maybe<T> : IEquatable<Maybe<T>> where T : class
  2. Compare with the default of T instead of null: public bool HasValue => _value != default(T);

But I can see that the second options has flaws on its own and might lead to other errors. Depending of the outcome I can create a PR.

linkdotnet avatar Apr 19 '19 21:04 linkdotnet

Could you give an example when the current implementation is problematic?

_value is currently wrapped into the MaybeValueWrapper class to avoid issues when T is a struct, hence _value != null should work in all situations.

vkhorikov avatar Apr 21 '19 10:04 vkhorikov

@vkhorikov please don't change the behavior of Maybe removing the support for struct.

I use it regularly to encapsulate int, DateTime etc and as demonstrated by issues #61 and #67 others do the same.

77it avatar Apr 21 '19 16:04 77it

Oh I didn't see the part with the MaybeValueWrapper. At this point you are obviously completely right. For me it is more a semantic "issue". What does it mean for a value-type to have no value? It seems counter-intuitiv (hence the name value type it provides always a value. So the null-check in Maybe.From doesn't make "sense" because T will be always not null).

If there are valid reasons or use cases I am totally fine.

I hope you got my point or my thought process behind this.

linkdotnet avatar Apr 21 '19 18:04 linkdotnet

@linkdotnet Hm, I can't remember why this null check is there, could be a relict from the older version where structs were not allowed. Would be good to come up with an example where this implementation could become problematic.

The reasoning for wrapping value types with Maybe is just to unify handling of nulls in code.

vkhorikov avatar Apr 26 '19 12:04 vkhorikov