This post grows out of my previous post on creating a C# equivalent to the Visual Basic With statement. I have since come up with a hand full of other lambda-accepting extension methods that do other handy things.
Improving on the With Statement
First off, the original with function can be extended to return values if need be as follows:
public static TReturn With<T,TReturn>(this T obj, Func<T, TReturn> action)
{
return action(obj);
} |
The As Method
The following As methods are very handy when you have a variable that is of one type but you need to perform some actions on it in the context of another type which the it also implements.
public static void As<T>(this object obj, Action<T> action)
{
action((T) obj);
}
public static TReturn As<T,TReturn>(this object obj, Func<T, TReturn> action)
{
return action((T) obj);
} |
IfIs, the Conditional form of As
What if you are not sure if the type you have can be cast to the other type? The following IfIs methods are just like the As method but only execute the code if the cast can be made.
public static void IfIs<T>(this object obj, Action<T> action)
{
if(obj is T)
action((T) obj);
}
public static TReturn IfIs<T,TReturn>(this object obj, Func<T, TReturn> action)
{
return obj is T ? action((T)obj) : default(TReturn);
} |
Again I can see that this sort of syntactical sugar may drive some people nuts. Others may just not see the need. But for some of us, this sort of thing makes it easier to write expressive code.