Skip to content

GeneralTypesExtensions

David Arno edited this page Feb 17, 2020 · 2 revisions

Null and casting extensions for general types, using Option<T>

AsNullable

public static T? AsNullable<T>(this Option<T> option) where T : struct

Converts an Option<T> to T?.

If option contains a value, then that value is returned. Otherwise null is returned. Note, this method is for structs only.

AsNullableRef

public static T? AsNullableRef<T>(this Option<T> option) where T : class

Converts an Option<T> to T?.

If option contains a value, then that value is returned. Otherwise null is returned. Note, this method is for classes only and only really makes sense when used with C# 8's nullable reference types feature.

ToOption

public static Option<T> ToOption<T>(this T obj)

Performs a null-checked conversion of obj to an Option<T>.

If obj is null, then an Option<T> containing none is returned. Otherwise, an Option<T> containing obj is returned. This method supports both nullable structs and classes (nullable reference types in C# 8).

TryCast

public static Option<T> TryCast<T>(this object value) where T : class

Attempts to cast value to T and converts the result to an Option<T>, using ToOption (above).

If value is of type T, and is not null, then an Option<T> containing value is returned. Otherwise an Option<T> containing none is returned.

Clone this wiki locally