Sunday, 11 March 2012

What is the difference between ToArray() and ToArray(this IEnumerable source) ?


Ex:
ArrayList arrint = new ArrayList();
//          arrint.Add(object obj)-àaccepts
            arrint.Add(10);
            arrint.Add(40);
            arrint.Add(50);
            foreach (int item in arrint)
            {
                Console.WriteLine(item);
            }
            int[] intarr = arrint.ToArray();---àError why because

Yes,we have difference ArrayList Collection can take any type of data as element because  arraylist accepts any accepts any data.
so when we make this ArrayList collection to an Array, the return type should be object[] .
class ArrayList
{
            public virtual object[] ToArray();
}

Ex:
We have one static method is called Enumerable in this we have one more method with the name
Class static Enumerable
{
public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source);
}

This is useful when we converting one type of Array to same type of array it can be integer array,string array,boolean arry then automatically conversation done.
Ex:
int[] intarr = new int[4];
            intarr[0] = 15;
            intarr[1] = 25;
            intarr[2] = 30;
            intarr[3] = 30;
            int[] explarr = intarr.ToArray<int>();

above Enumerable static class adds an extension method to Interface
public interface IEnumerable<T> : IEnumerable
    {       
        IEnumerator<T> GetEnumerator();
    }
So any type of data as per T the conversion will be done. Till now we seen adding extension methods to existing classes now above example saying we can add extension method to interface also.

which will return an apporiate type of array now not an object array like ArrayList ToArray() method.
This same things Ex1 amd Ex2 are for all type of array.
As we know using IEnumerable we can possible to iterate as interface based iteration.

No comments:

Post a Comment