What is meant by Generics?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ganesh22
    Banned
    New Member
    • Sep 2007
    • 81

    What is meant by Generics?

    What is ment by Generics? How we can define as Generics in Programaticall way?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Some reading is required here.

    Generally they help in type checking. i.e Using generics allows the compiler to help you check the correctness of your code by inferring information from the specified types. They also make your programming easier by not having to put a lot of casts. e.g
    if you do
    Code:
    ArrayList a = new ArrayList();
    a.Add("test");
    You cannot do
    Code:
    string s = a[0];
    even if you know that the object there is a string.
    You have to use
    Code:
    string s = (string)a[0];
    With generics that is not required, you simply do
    Code:
    List<string> a = new List();
    a.Add("test");
    string s = a[0];
    From now on the compiler will be helping you by inserting the casts where required and also stopping you from putting non-strings in that List.

    Comment

    • stoogots2
      New Member
      • Sep 2007
      • 77

      #3
      Good example. Generics also promote flexibility and performance. Remember when you cast (string) or (int), that is a computationally expensive process, something like 4 times slower than just assigning a value.

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        Originally posted by stoogots2
        Good example. Generics also promote flexibility and performance. Remember when you cast (string) or (int), that is a computationally expensive process, something like 4 times slower than just assigning a value.
        I missed the performance part because I had my Java cap when I typed that reply. (In Java erasure replaces all those generic types with raw types for interoperabilit y with legacy code)

        Comment

        • cloud255
          Recognized Expert Contributor
          • Jun 2008
          • 427

          #5
          Correct me if i am wrong, but as far as i can tell C# generics are exactly the same thing as C++ Templates?

          Comment

          • r035198x
            MVP
            • Sep 2006
            • 13225

            #6
            Originally posted by cloud255
            Correct me if i am wrong, but as far as i can tell C# generics are exactly the same thing as C++ Templates?
            "C# generics vs C++ templates" gives some interesting pages on Google.
            Last edited by Plater; Jun 23 '08, 02:29 PM. Reason: vc = vs

            Comment

            Working...