Tuesday, 21 February 2012

LINQ: Extension Methods for Console apps

When designing Console apps for Windows, we usually write a lot of message to the console. It is a pain to write “Console.WriteLine(“xxxxxx”)” every time.

So let’s use extension methods to ease the pain.

Step 1> Create a Library project, add a class:

namespace LINQ.ExtensionMethods
{
    public static class MExtensions
    {
        public static void Write(this string s)
        {
            Console.WriteLine(s);
        }
    }
}


Step 2> Create a Console project, in the Main method:

        static void Main(string[] args)
        {
            "Welcome to Console project".Write();
        }


image



Let’s do this for a collection, no more writing loops or calling a method to iterate. Here we write an extension method for IEnumerable<T> in the class MExtensions above.

  public static void Write<T>(this IEnumerable<T> c)
        {
            Console.WriteLine();
            foreach (var item in c)
            {
                Console.WriteLine(item);
            }
        }

And to call:

    string[] games = { "Soccer", "Football", "Rugby" };
    var items = games.Select(p => new { p, p.Length });
    items.Write();

image

No comments:

Post a Comment

Note: only a member of this blog may post a comment.