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

IfIs<T>

optionally executes an Action if the object is of the given type.

Source

/// <summary>
/// allows an action to be taken on an object if it is castable as the given type, with no return value.
/// if the target does not match the type, does nothing
/// </summary>
public static void IfIs<T>( this object target, Action<T> method )
    where T : class
{
    var cast = target as T;
    if ( cast != null )
    {
        method( cast );
    }
}

/// <summary>
/// allows an action to be taken on an object if it is castable as the given type, with a return value.
/// if the target does not match the type, returns default(T)
/// </summary>
public static TResult IfIs<T, TResult>( this object target, Func<T, TResult> method )
    where T : class
{
    var cast = target as T;
    if ( cast != null )
    {
        return method( cast );
    }
    else
    {
        return default( TResult );
    }
}

Example

item.IfIs<ILogicalDelete>( x => x.DeletedBy = User.Identity.Name );

var username = item.IfIs<IIdentity>( x => x.Name );

Author: dave thieben

Submitted on: 24 okt 2010

Language: C#

Type: System.Object

Views: 2955