A Great Use For Lambdas in C#

If you are writing a console application in C# that has to write a lot of output from different places in your code, then that's is one situation that illustrates a great use for lambda expression.

Consider the following code:

static Action<object> WL = obj => Console.WriteLine(obj);

What's happening in the above line of code is that you declared a System.Action<T> delegate that expects a T, or an object in our case, as a parameters and returns a void. You then assigned a lambda expression to that delegate in the format of obj => Console.WriteLine(obj). Now, every time you need to write out some text to the console, all you have to do is call WL("some text"), and that saves you from writing Console.WriteLine("some text") all the time.

If you have other examples of the uses for lambdas or find anything wrong with this post, I would love to hear it.


Comments powered by Disqus