C# - Getting rid of casting-parenthesis

Normally casting should be avoided if possible and when casting is necessary, use the as-operater and check the result for null! But sometimes a plain cast seems to be valid and necessary and when this is the case, I absolutely hate to type the parenthesis. So my new little friend is this extension method:

public static class CastExtension
{
    public static T Cast<T>(this object obj)
    {
        return (T) obj;
    }
}

instead of:

((IBar) foo).DoSomething();

you can now trade two parenthesis for two angle brackets:

foo.Cast<IBar>().DoSomething().

Doesn't seem to be much of a difference, but it types much nicer!

Tags

Posted in | Posted on 01 Feb 2010 12:01by Tobi | no comments

Comments

Leave a comment