What is difference b/w Generic List and Arraylist, Generic List Vs HashTable, Generic List Vs No Generic?

前端 未结 2 427
北海茫月
北海茫月 2020-12-12 06:52

What is difference between

  1. Generic List and Arraylist
  2. Generic List Vs HashTable
  3. Generic List Vs No Generic?
相关标签:
2条回答
  • 2020-12-12 07:22

    The ArrayList and HashTable types were included in .Net 1.0. They are more or less equivalent to a List and a Dictionary.

    They both exists to keep compatibility with code written in .Net 1.0 or 1.1 before generics were introduced in 2.0, and should generally be avoided if you target .Net 2.0 or later.

    0 讨论(0)
  • 2020-12-12 07:31

    Basically, generic collections are type-safe at compile time: you specify which type of object the collection should contain, and the type system will make sure you only put that kind of object in it. Furthermore, you don't need to cast the item when you get it out.

    As an example, suppose we wanted a collection of strings. We could use ArrayList like this:

    ArrayList list = new ArrayList();
    list.Add("hello");
    list.Add(new Button()); // Oops! That's not meant to be there...
    ...
    string firstEntry = (string) list[0];
    

    But a List<string> will prevent the invalid entry and avoid the cast:

    List<string> list = new List<string>();
    list.Add("hello");
    list.Add(new Button()); // This won't compile
    ...
    // No need for a cast; guaranteed to be type-safe... although it
    // will still throw an exception if the list is empty
    string firstEntry = list[0];
    

    Note that generic collections are just one example (albeit the most commonly used one) of the more general feature of generics, which allow you to parameterize a type or method by the type of data it deals with.

    0 讨论(0)
提交回复
热议问题