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

IfNotNull<T, TResult>

if the object this method is called on is not null, runs the given function and returns the value. if the object is null, returns default(TResult).

Source

/// <summary>
/// if the object this method is called on is not null, runs the given function and returns the value.
/// if the object is null, returns default(TResult)
/// </summary>
public static TResult IfNotNull<T, TResult>( this T target, Func<T, TResult> getValue )
{
    if ( target != null )
        return getValue( target );
    else
        return default( TResult );
}

Example

var username = HttpContext.Current.IfNotNull( ctx => ctx.User.IfNotNull( user => user.Identity.IfNotNull( iden => iden.Name ) ) );

Author: dave thieben

Submitted on: 24 okt 2010

Language: C#

Type: System.Object

Views: 13847