The C# 3 has somewhat revolutionised the way we use to write
anonymous method. I am almost ready to say that lambda expression has rendered
anonymous method “obsolete”. I agree that there are restrictions in anonymous methods
such as it should be inline and cannot have multiple statements.
The scope of this post is not to discuss about anonymous
methods, but to look at much neater way of writing static utility methods.
Please welcome Extension methods!
The development community have a wide range of ideas about
extension methods, and some goes all the way of discounting it from the
development toolset. I was reading the chapter on extension methods in Jon
Skeet’s C# In Depth 2ed Edition (which I have to say probably one of the best
investments I have done), and would like to share an example that I saw in this
book. See below.
C# In-Depth 2ed Edition – Jon Skeet (Chapter 10)
public class Test
{
static void Main()
{
object y = null;
Console.WriteLine(y.IsNull());
y = new object();
Console.WriteLine(y.IsNull());
}
}
public static class NullUtil
{
public static bool IsNull(this object x)
{
return x == null;
}
}
{
static void Main()
{
object y = null;
Console.WriteLine(y.IsNull());
y = new object();
Console.WriteLine(y.IsNull());
}
}
public static class NullUtil
{
public static bool IsNull(this object x)
{
return x == null;
}
}
Looking at the above code for the first time gave be the
frights! For the C# gurus out there, it might be a piece of cake!
To the naked eye this code looks crazy, but for the person who
knows the key concepts of extension methods, this is a simple exercise.
Consider the following piece of code (from LinqPad).
void Main()
{
IEnumerable<int> myEnumerable = null;
var
fives = myEnumerable
.EmptyIfNull()
.Where(x => x == 5)
.ToList();
fives.Dump();
}
//
Define other methods and classes here
public static class EnumerableEx
{
public static IEnumerable<T> EmptyIfNull<T>(this
IEnumerable<T> enumerable)
{
return enumerable ?? Enumerable.Empty<T>();
}
}
Please do not tell me that the above code is not sweet! I
agree that this depends on the business case, but consider the possibilities.
How often do you use FirstOrDefault() and check whether the return value is
null.
No comments:
Post a Comment