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

IfType

Execute code only on certain types

Source

public static void IfType<T>(this object item, Action<T> action) where T : class
{
    if (item is T)
    {
        action(item as T);
    }
}

Example

target.IfType<ItemDoesNotExistNavigationTarget>(x => ShowFeedback(x.Message));

the action is only executed when called on a certain type. It Replaces type checking AND casting like this:

if (target is ItemDoesNotExistNavigationTarget){
  ShowFeedback(((ItemDoesNotExistNavigationTarget).Message));
}

Author: Loek van den Ouweland

Submitted on: 5 sep 2014

Language: C#

Type: object

Views: 3067