Monday 15 September 2014

Generics in c# with examples | Generics demo

Generics are type safe because there is no boxing and unboxing so
i will take  single datatype not heterogeneous like array list
so execution will be faster compare to collections.
Just we need to import System.collection.generics;


 private void PrivateGenerics()
    {
        List<int> newlist = new List<int>(); //declaring generics type int
        newlist.Add(3); // adding values
        //newlist.Add("5"); //will give compile time error;
        newlist.Add(2);
        int i = Convert.ToInt32("5"); 
        newlist.Add(i);
        newlist.Insert(0, 7); // giving index for in flow.
        newlist.Insert(1, 900000001);
        newlist.Insert(2, 900000002);
        newlist.Add(20);
        foreach (int myValue in newlist)
        {
            Response.Write(myValue +"<br/>");
        }

    }


 newlist.Sort();
        foreach (int myValue in newlist)
        {
            Response.Write(myValue +"<br/>");
        }
Generics With Array List .here i have shown how to add your arrayList in List<type int>
.

ArrayList Myarlist = new ArrayList();
        Myarlist.Insert(0, 40);
        Myarlist.Insert(1, 45);
        //Myarlist.Insert(2, "raj");
        var list = Myarlist.Cast<int>().ToList();//to add arraylist in list
        newlist.InsertRange(3, list);
        foreach (int myValue in newlist)
        {
            Response.Write(myValue +"<br/>");
        }


Now last code we added int value in array List so it works Fine.
Now we are going to add one string value in ArrayList And then See what would be
result.will it gives result or  there will be error.
Its showing Error because we have done casting of Arraylist to
integer type but we are providing String value also.


Share This
Previous Post
Next Post

FYJC XI standard online admisson Process and declaraton of Merit list . Cut off List For prevous year also . 10 Th Results onlne declaraton Maharashtra Region .

0 comments: