I've implemented a Maybe<T> class which implements IEnumerable in C# inspired by Mark Seemann and it works great. I've got a suite of helper extension methods that make common operations Maybe-friendly and they all work great too. I had the idea to change Maybe<T> from a class to a struct to prevent it from being nullable and it seems to work great with one problem:
var inputs = new Maybe<string>[] { /* from somewhere */ };
// This line works with class Maybe and struct Maybe
var results1 = inputs.SelectMany(x => ParseMaybe.ToInt32(x));
// This line works with class Maybe but with struct Maybe it yields a compiler error:
// Error CS0407 'Maybe<int> ParseMaybe.ToInt32(string)' has the wrong return type
var results2 = inputs.SelectMany(ParseMaybe.ToInt32);
Note: Because Maybe implements IEnumerable here, I'm using SelectMany instead of Select.
This code works with the class version but gets the compiler error as a struct. Why?
structandclassimplementation?SelectManyis used to flatten nested collections. You should useSelecthere, otherwise you will get an enumeration of chars.