Friday, 1 June 2012

What are the Extension methods(conversion methods) have different singnatures?

We have many Extension methods in which are defined in System.Linq namespace and Enumerable static class.

This Enumerable static class contains few Conversion methods defined as Extension methods(static methods)
Ex : ToArray(),ToList(),ToDictionary(),ToLookup()….are conversion methods as well Extension methods.

Example :

ToList() : this method is used convert the data to List type.which has 2 singnatures.which signature we need to consider? .

Demo1:

  int[] intarr1 = { 200, 450, 890, 874 };
   IList<int> list1 = intarr1.ToList<int>();
   foreach (int item in list1)
   {
                Console.WriteLine(item);
    }
Out put : 200, 450, 890, 874

Note:IEnumerable<int> listarr = intarr.ToList<int>();// also working
not good because IEnumerable is base for IList;

the above work we can perform using ToList() also like below

Demo2:

int[] intarr2 = { 200, 450, 890, 874 };
            IList<int> list2 = intarr2.ToList();
            foreach (int item in list2)
            {
                Console.WriteLine(item);
            }
Out put : 200, 450, 890, 874 // both output are same. Yes so

What the difference between ToList<source>() and ToList() signatures?

In above example we know intarr1 object is an array of intgeter type so can able to write

   IList<int> list1 = intarr1.ToList<int>();

When we don’t know the source type data is it string array, boolean array,double array..ect we simple use


            IList<int> list2 = intarr2.ToList();

ToList() says the return type takes as IList<int> like above but

Coming to an object which contains different types of data then we have to use


ToList() type example is below

Demo3:

  object[] diffdata = { 105, "asp.net", true, "asp.net mvc" };
   var intarrtolist = diffdata.ToList(); // var
 foreach (var item in diffdata)
{
Console.WriteLine(item);
               
}
Here we want to iterate any type of data. So return type should be var,like above.

Convert to list type which tells return type as intellience

So finally ToList() signature is useful when we want to iterate through different types of data means what type of data in that given object when we don’t know.


We can prepare an object using Linq query also like below

Var object say we have to take what type of data is return type when change to list type.

  int[] intarr4 = { 200, 450, 890, 874 };
  var data = from n in intarr4 select n;
           
            foreach (int item in data)
            {
                Console.WriteLine(item);
            }


Var object( data) also say what we have to take as a return type as intellisense.
The same is applicable to all conversion extension types.

No comments:

Post a Comment