DCSIMG
C# Lambda and Extensions to help around Casting - Zuker On Foundations

Zuker On Foundations

The realm of .NET (WPF, WCF and all around)
C# Lambda and Extensions to help around Casting

One of the common scenarios of casting in daily use of code is the need to check if an instance is of a given type, if so - perform actions on it.

Some developers tend to do as following:

if (foo is Bar)
{
    Bar b1 = (Bar)foo;
    //Do Stuff..
}

A word about it - this approach is condered wasteful in this case.
This is because the result of whether the instance is of a 'Bar' type is not the only thing that matters in this case, meaning I still need to cast it and perform actions on it as 'Bar' type.

This is better in this case:

Bar b2 = foo as Bar;
if (b2 != null)
{
   //Do Stuff
}

In this example, we first perform the cast, next we then simpy check if the casting succeeded.

I decided to write a small helper for this common thing.

Step 1 - Try Cast

public static bool TryCast<T>(object source, out T target) where T : class
{
    target = source
as T;
    return (target != null);
}

//playing around - step 1
Bar b3;
if (Extensions.TryCast<Bar>(foo, out b3))
{
    //Do stuff
}

Step 2 - Try Cast & Perform

public static void TryCastPerform<T>(object source, Action<T> action) where T : class
{
    T cast;
    if (TryCast<T>(source, out cast))
    {
        action(cast);
    }
}

//playing around - step 2
Extensions.TryCastPerform(foo,
    (
Bar b4) =>
    {
       //Do Stuff
    });

Using Extensions:
Step 3 - Try Cast & Perform Extension

public static void TryCastPerformExt<T>(this object source, Action<T> action) where T : class
{
    TryCastPerform<T>(source, action);
}

//playing around - step 3
foo.TryCastPerformExt((Bar b5) =>
{
   //Do Stuff
});

Sample code is attached
To download the attached files you should follow to the same post in my prior blog. (http://blogs.windowsclient.net/zuker)

Published Thursday, January 15, 2009 3:25 PM by Amir Zuker

תגים:,

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: