Search code examples
c#genericsboxing

Does .Net typecast when an object is used in collection using generics?


Does .net CLR typecast the objects to the ones mentioned in the collection declaration? If i declare a

List<string> lststrs= new List<string>();
lststrs.add("ssdfsf");

does .net typecasts this object while adding and retriving?????

Well i think the question itself was not clearly understood by everyone.Let me elaborate. In java there is generics ,but if you decompile the code you will notice that ,the compiler places a typecast everywhere the Collection object is used. For Ex: List listOfStrings; listOfStrings.add(""); String value = listOfStrings.get(1); After decompiling the class file we see this List listOfStrings; listOfStrings.add(""); String value = (String)listOfStrings.get(1); Here the compiler has palced the typecast for string.

Now my question is whether it is same in .Net??


Solution

  • Do you mean this?

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

    List is a generic type - if you declare like below you'll get a compialtion error:

    List myList = new List(); //<-- big mama of a compilation error
    

    Anyway - since it's a generic List it is strongly typed, so you won't be able to pass-in anything that's not a string (if you do so it will result - again - in a big mama of a compilation error).