concept Some in category c#

appears as: Some
Functional Programming in C#: How to write better C# code

This is an excerpt from Manning's book Functional Programming in C#: How to write better C# code.

Different functional frameworks use varying terminology to express similar concepts. A common synonym for Option is Maybe, with the Some and None states called Just and Nothing respectively.

Listing 3.5. Implementing the Some and None types

The F class is meant as the entry point for client code; it exposes the value None, which is the empty option, and the function Some, which will wrap a given T into a Some<T>.

None represents the absence of a value, so it’s a type with no instance fields. Just like Unit, there’s only one possible value for None. Some has a single field that holds the inner value; this can’t be null.

The preceding code allows you to explicitly create values in the None or Some state:

Partial functions are problematic because it’s not clear what the function should do when given an input for which it can’t compute a result? The Option type offers a perfect solution to model such cases: if the function is defined for the given input, it returns a Some wrapping the result; otherwise, it returns None.

Lookup takes a NameValueCollection and a string (the key), and will return Some with the value if the key exists, and None otherwise. Here’s the implementation:

public static Option<string> Lookup
   (this NameValueCollection @this, string key)
   => @this[key];

That’s it! The expression @this[key] is of type string, whereas the return value is Option<string>, so the string value will be implicitly converted into an Option<string>. (Remember, in the implementation of Option shown earlier, implicit conversion from a value T to an Option<T> was defined to return None if the value was null, and to lift the value into a Some otherwise.) We’ve gone from a null-based API to an Option-based API.