XDracam / unity-corelibrary

Collection of classes and extension methods that make life with Unity3D more comfortable
MIT License
16 stars 3 forks source link

IfNotNull #47

Closed Gollorum closed 5 years ago

Gollorum commented 5 years ago

In addition to UtilityExtensions.IsNull<T>(this T value), add the extension method IfNotNull which invokes a given Func or Action if IsNull returns false:

public static void IfNotNull<T>(
    this T value, 
    Action<T> action, 
    Action elseAction = null
) where T : class {
    if (!value.IsNull()) action(value);
    else if (elseAction != null) elseAction();
}

public static TResult IfNotNull<T, TResult>(
    this T value, 
    Func<T, TResult> action, 
    Func<TResult> elseAction
) where T : class {
    if (!value.IsNull()) return action(value);
    else return elseAction();
}

public static TResult IfNotNull<T, TResult>(
    this T value, 
    Func<T, TResult> action, 
    TResult elseResult = default(TResult)
) where T : class
    => IfNotNull(value, action, () => elseResult);
XDracam commented 5 years ago

Edited, documented and merged