What are Generics? what do I get from them?

If anybody can provide a sample code, much better.

Thanks,

Omar




Answer this question

What are Generics? what do I get from them?

  • Laxmi.

    generics is new in .NET 2.0. It allows you to make a safe strong typed collection and allows you to use them similar to say an arraylist such as adding/removing objects. you can only store objects of a certain type in this collection and nothing else, otherwise you will get a compiler error

    List<string> theStringCollection = new List<string>();

    theStringCollection.Add("hi"); //correct

    theStringCollection.Add(1); //compiler error - because its not a string. it has to be a string because thats what the collection type is.

    another example, if we have an class called "person", we can only hold objects that are of type person:

    Person person1 = new Person(); //example

    List<Person> theCollection = new List<Person>();

    theCollection.Add(person1);

    you can remove an object:

    theCollection.Remove(personObject)

    and there are also many functions in the List<T> class:

    http://msdn2.microsoft.com/en-us/library/6sh2ey19.aspx



  • Nick Darnell

    a "Person" is just a class type :-) Like String or Int. You are creating a List generic of the type you specify and can only store that type of object, so if you had "Person" then you can only store in there objects of type person

  • Thomas Ivarsson

    thank you ahmedilays,

    What I am trying to understand is the 'scope' and 'definition' of this 'Person' class type. When you specify, for example the integer type, you can only have elements that are of the integer type. If you try to add a string element to the collection, you get a compiler error and this is what i mean by definition and scope.

    How is the scope and definition of a class or object type determined in generics And when you add a Person or Car class or object type to the list what would the code look like Let me know if my question don't make sense.

    Thank you


  • tonhinbm

    Hi

    another example, if we have an class called "person", we can only hold objects that are of type person: Person person1 = new Person(); //example List theCollection = new List(); theCollection.Add(person1);

    Could you please explain what 'Person type' means I know what datatype means but when you have a Person type, does this mean that you must name your element as person1 no matter how many elements you intend to add to the generic list

    thank you


  • What are Generics? what do I get from them?