DigitecGalaxus / Galaxus.Functional

A package bringing popular functional abstractions (e.g. Option or Result) to C#.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Consider an Option.Some constructor relying on type inference.

FreeApophis opened this issue · comments

The type constructor of None currently is very verbose. You always have to give the type information of the inner type. This is not necessary in the some case, the type can be inferred from the value.

Instead of

var option = Option<TSource>.Some(value);

It should look like this:

var option = Option.Some(value);

I thought the same when I first used this library, and actually got around to thinking of an implementation. The only part I don't like about it is that the class Option has no relation to Option<T>, but that may just be my object oriented brain making me think it's bad.

public class Option
{
    public static Option<T> Some<T>(T value) => Option<T>.Some(value);
}

This is an incredibly simple and possibly naïve implementation, but it at least allows me write var option = Option.Some(value);.

The class can be static too, this might help your OO mind ;)

Why do I think this not useful?
We can only call the Option.Some(value) constructor if we already have a value. At that point we might as well do value.ToOption() or value.ToOption<T>(). This works even if the value (or reference) is null.

Why this might still be a good idea:
Option<T>.Some(value) is basically the counterpart to value.ToOption<T>(). But there is currently no counterpart for value.ToOption().

My opinion:
We could add Option.Some(value) to act as a counterpart to value.ToOption() even if the latter is already a very short (and my preferred) way of doing it.