Thursday, 1 March 2012

What is Extension Method in Linq any Example?

Yes,we have so many extension methods available in .net. not only Extension Methods belongs to Linq. Extension methods are used to extension the funcationality of existing types[classes]. Linq has so many Extension methods to extened the functionality of Linq. Linq awareness is improved by added the Extension methods to existing libraries in later version of dotnet.

Definication: An extension method is available to call on any object instance that is convertible to the type of the method's first parameter.

Extension Methods-->Added Funcationalities.
Ex:
            string[] str = { "dafs", "dafsd", "ewrw" };
             IEnumerable<string>   ss = str.Cast<string>();
             IEnumerator<string> sr=ss.GetEnumerator();
             while (sr.MoveNext())
             {
                 string s = sr.Current;
                 Console.WriteLine(s);
             }
             Console.WriteLine("Cast<int>()-->casts the type insideCast<casttype>");
             int[] intarr = { 10, 100, 200, 300 };
             IEnumerable<int> sintrr = intarr.Cast<int>();
             IEnumerator<int> ir = sintrr.GetEnumerator();
             while (ir.MoveNext())
             {
                 int  m = ir.Current;
                 Console.WriteLine(m);
             }
             Console.ReadKey();
But Cast<TResult>() is definied only once. as a generic method.
like  Cast<int>()  we have so many extension methods we have which are all these  extension methods extend IEnumerable<T> and IQueryable<T> to implement the standard query operators. Now we  seen above how Cast<T> is implement the IEnumerable<T> .


Note: don't write any logics for performaning any simple task also if we have any existing methods[extension methods] in dotnet.

No comments:

Post a Comment