ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

IfNotNull

Returns a selected value when the source is not null; null otherwise.

Source

/// <summary>
///   Returns a selected value when the source is not null; null otherwise.
/// </summary>
/// <typeparam name = "T">Type of the source object.</typeparam>
/// <typeparam name = "TInner">Type of the object which the selector returns.</typeparam>
/// <param name = "source">The source for this extension method.</param>
/// <param name = "selector">A function which given the source object, returns a selected value.</param>
/// <returns>The selected value when source is not null; null otherwise.</returns>
public static TInner IfNotNull<T, TInner>( this T source, Func<T, TInner> selector )
	where T : class
{
	return source != null ? selector( source ) : default( TInner );
}

Example

class A
{
    public B Inner { get; set; }
}
A a = null;
B getB = a.IfNotNull( x => x.Inner );

Author: Steven Jeuris

Submitted on: 15 nov 2011

Language: C#

Type: System.Object

Views: 5828