Friday, May 29, 2009

A note on LINQ

  • Today I would like to discuss about the Technology LINQ(Language Integrated Query). The unique way of programming for any type of the data source.

    Currently LINQ comes with the following flavors.

    LINQ to Objects
    LINQ to Entities
    LINQ to SQL
    LINQ to Entity framework
    LINQ to XML

    Today let me describe about the current way of coding and then we will refactor the code by using LINQ flavor.

    Problem statement:

    I want to get the names from the array whose name starts with “V”

    Current way of coding….

    private static void GetNamesWhichStartswithV()
    string[] Names = new string[] {
    "Vinayaka Shenoy",
    "Madhava Shenoy",
    "Vijethry Shenoy",
    "Divya Shenoy",
    "Krishna Shenoy",
    "Jayalaxmi Shenoy",
    "Chandrakala Shenoy",
    "Gurudath Kamath"

    List NamesWithV = new List();
    for (int i = 0; i < names =" new">NamesWithVLinq = from n in Names
    Wheren .StartsWith("V")
    select n;


    How easy and cool stuff right?

    So why you guys are waiting for, start using/exploring LINQ…..

    Happy LINQ programming…..


Wednesday, May 20, 2009

Extension Methods in C#

Today I would like talk about why,how and where abouts of extension methods.

Lets think about the world where we didn’t had Extension methods and how we were coding for the business problems, lets discuss about that with the example

Suppose I have a number which is of type integer and I have to find that, whether the given number is even or not.

Ideal way to program is as shown below.

C# code snippet

Now think of the case, where if you get some thing to check whether the number is even on the given type itself, in this case on int (for example number.IsEven() ) how easy our job would have been.

If you thought about this opportunity, here goes an extension method for you.

Above stuff can be achieved with the extension method concept as shown below..

So cool right?

So now what next, If I have to write my own extension method on a particular type how should I go about it
Rules :
1) I need to have a static classs( Name could be any thing which you wish)
2) I need to have a static method as shown above with the “this” keyword followed by the type to extend.

That’s it!!

Now lets talk about the hidden secret of the Extension method….

Think about the case where we will have both the extension method and instance method on a particular type, on invocation of the method on that type which one will get fired?????

Can you guesss??????

It is the instance method not the Extension Method…..