Let's say I have a set of sources that supply an array of tagged items where the type of the item varies from source to source. I want to create a default implementation of the source method, but I haven't been able to find a way to do so without getting a compiler warning about unchecked conversions.  To begin with, here's my generic tagged item:  public class TaggedItem&lt;T&gt; {     private final String tag;     private final T item;     public TaggedItem(String tag, T item) {         this.tag = tag;         this.item = item;     }     public String getTag() { return tag; }     public T getItem() { return item; } }   and a sample concrete implementation where the item type is String:  public class TaggedString extends TaggedItem&lt;String&gt; {     public TaggedString(String tag, String item) {         super(tag, item);     } }   Now here's my generic source interface:  public interface ITaggedItemSource&lt;T&gt; {     default TaggedItem&lt;T&gt;[] getTaggedItems() {         return new TaggedItem[0]; // (1)     }     default TaggedItem&lt;T&gt;[] getTaggedItems(Class&lt;TaggedItem&lt;T&gt;&gt; clazz) {         return (TaggedItem&lt;T&gt;[])Array.newInstance(clazz, 0); // (2)     }     default List&lt;TaggedItem&lt;T&gt;&gt; getTaggedItemList() {         return new ArrayList&lt;TaggedItem&lt;T&gt;&gt;();     } }   I began with the first method. However this causes the following compiler warning at (1):  Type safety: The expression of type TaggedItem[] needs unchecked conversion to conform to TaggedItem&lt;T&gt;[]   So I added the second method. However this causes the following compiler warning at (2)  Type safety: Unchecked cast from Object to TaggedItem&lt;T&gt;[]   Finally, for the third method, I converted my array to a List and I was warning free.  For the record, here's an example of a concrete source.  public class TaggedStringSource implements ITaggedItemSource&lt;String&gt; {     @Override     public TaggedItem&lt;String&gt;[] getTaggedItems() {         TaggedString[] items = new TaggedString[1];         items[0] = new TaggedString("t1", "data");         return items;     }     @Override     public TaggedItem&lt;String&gt;[] getTaggedItems(Class&lt;TaggedItem&lt;String&gt;&gt; clazz) {         TaggedString[] items = new TaggedString[1];         items[0] = new TaggedString("t1", "data");         return items;     }     @Override     public List&lt;TaggedItem&lt;String&gt;&gt; getItemList() {         List&lt;TaggedItem&lt;String&gt;&gt; items = new ArrayList&lt;&gt;();         items.add(new TaggedString("t1", "data"));         return items;     }    I should note that both the default array and List implementations work just fine despite the compiler warnings. (As you'd expect I suppose, after all, they're just warnings.)  My questions are:   Is it possible to have a method that uses arrays that does not cause a warning? If so, how? Why is it possible to avoid a warning when using Lists?
7545
Due to the implementation of Java generics, you can't have code like this:   public class GenSet&lt;E&gt; {     private E a[];      public GenSet() {         a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation     } }   How can I implement this while maintaining type safety?  I saw a solution on the Java forums that goes like this:  import java.lang.reflect.Array;  class Stack&lt;T&gt; {     public Stack(Class&lt;T&gt; clazz, int capacity) {         array = (T[])Array.newInstance(clazz, capacity);     }      private final T[] array; }   But I really don't get what's going on.
40529
Assume the following type definitions:  public interface IFoo&lt;T&gt; : IBar&lt;T&gt; {} public class Foo&lt;T&gt; : IFoo&lt;T&gt; {}   How do I find out whether the type Foo implements the generic interface IBar&lt;T&gt; when only the mangled type is available?
63337
Is there a short way of converting a strongly typed List&lt;T&gt; to an Array of the same type, e.g.: List&lt;MyClass&gt; to MyClass[]?  By short i mean one method call, or at least shorter than:  MyClass[] myArray = new MyClass[list.Count]; int i = 0; foreach (MyClass myClass in list) {     myArray[i++] = myClass; }
1947
What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?  Consider the following sample code - inside the Example() method, what's the most concise way to invoke GenericMethod&lt;T&gt;() using the Type stored in the myType variable?  public class Sample {     public void Example(string typeName)     {         Type myType = FindType(typeName);          // What goes here to call GenericMethod&lt;T&gt;()?         GenericMethod&lt;myType&gt;(); // This doesn't work          // What changes to call StaticMethod&lt;T&gt;()?         Sample.StaticMethod&lt;myType&gt;(); // This also doesn't work     }      public void GenericMethod&lt;T&gt;()     {         // ...     }      public static void StaticMethod&lt;T&gt;()     {         //...     } }
104904
I really should be able to get this, but I'm just to the point where I think it'd be easier to ask.  In the C# function:  public static T GetValue&lt;T&gt;(String value) where T:new() {    //Magic happens here }   What's a good implementation for the magic? The idea behind this is that I have xml to parse and the desired values are often primitives (bool, int, string, etc.) and this is the perfect place to use generics... but a simple solution is eluding me at the moment.  btw, here's a sample of the xml I'd need to parse  &lt;Items&gt;     &lt;item&gt;         &lt;ItemType&gt;PIANO&lt;/ItemType&gt;         &lt;Name&gt;A Yamaha piano&lt;/Name&gt;         &lt;properties&gt;             &lt;allowUpdates&gt;false&lt;/allowUpdates&gt;             &lt;allowCopy&gt;true&lt;/allowCopy&gt;         &lt;/properties&gt;        &lt;/item&gt;     &lt;item&gt;         &lt;ItemType&gt;PIANO_BENCH&lt;/ItemType&gt;         &lt;Name&gt;A black piano bench&lt;/Name&gt;         &lt;properties&gt;             &lt;allowUpdates&gt;true&lt;/allowUpdates&gt;             &lt;allowCopy&gt;false&lt;/allowCopy&gt;             &lt;url&gt;www.yamaha.com&lt;/url&gt;         &lt;/properties&gt;     &lt;/item&gt;     &lt;item&gt;         &lt;ItemType&gt;DESK_LAMP&lt;/ItemType&gt;         &lt;Name&gt;A Verilux desk lamp&lt;/Name&gt;         &lt;properties&gt;             &lt;allowUpdates&gt;true&lt;/allowUpdates&gt;             &lt;allowCopy&gt;true&lt;/allowCopy&gt;             &lt;quantity&gt;2&lt;/quantity&gt;         &lt;/properties&gt;     &lt;/item&gt; &lt;/Items&gt;
5983
The title is kind of obscure. What I want to know is if this is possible:  string typeName = &lt;read type name from somwhere&gt;; Type myType = Type.GetType(typeName);  MyGenericClass&lt;myType&gt; myGenericClass = new MyGenericClass&lt;myType&gt;();   Obviously, MyGenericClass is described as:  public class MyGenericClass&lt;T&gt;   Right now, the compiler complains that 'The type or namespace 'myType' could not be found." There has got to be a way to do this.
5349
I'm using reflection to loop through a Type's properties and set certain types to their default.  Now, I could do a switch on the type and set the default(Type) explicitly, but I'd rather do it in one line.  Is there a programmatic equivalent of default?
112618
This causes a compile-time exception:  public sealed class ValidatesAttribute&lt;T&gt; : Attribute {  }  [Validates&lt;string&gt;] public static class StringValidation {  }   I realize C# does not support generic attributes. However, after much Googling, I can't seem to find the reason.  Does anyone know why generic types cannot derive from Attribute? Any theories?
18992
I'm developing an application where I the need to invoke a method of a generic class and I don't care about the instances actual type. Something like the following Java code:  public class Item&lt;T&gt;{   private T item;    public doSomething(){...} }  ... public void processItems(Item&lt;?&gt;[] items){  for(Item&lt;?&gt; item : items)    item.doSomething(); }   At the time I was on a hurry, so I solved my problem by defining a interface with the methods I needed to invoke and made the generic class implement it.  public interface IItem   {    void doSomething(); }  public class Item&lt;T&gt; : IItem {   private T item;    public void doSomething(){...} }  ... public void processItems(IItem[] items) {  foreach(IItem item in items)    item.doSomething(); }   This workaround works fine, but I'd like to know what is the correct way to achieve the same behavior.    EDIT:  I forgot to refer that the caller of processItems doesn't know the actual types. Actually the idea was that the array passed as argument to processItems could contain intermixed types. Since its not possible to have such an array in .Net, using a non generic base class or interface seems to be the only way.
9792
Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java.  And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing...  Here's the problem I was given:  /* What is the output of the following program? */  public class Test {    public boolean equals( Test other ) {     System.out.println( "Inside of Test.equals" );     return false;   }    public static void main( String [] args ) {     Object t1 = new Test();     Object t2 = new Test();     Test t3 = new Test();     Object o1 = new Object();      int count = 0;     System.out.println( count++ );// prints 0     t1.equals( t2 ) ;     System.out.println( count++ );// prints 1     t1.equals( t3 );     System.out.println( count++ );// prints 2     t3.equals( o1 );     System.out.println( count++ );// prints 3     t3.equals(t3);     System.out.println( count++ );// prints 4     t3.equals(t2);   } }   I asserted that the output should have been two separate print statements from within the overridden equals() method: at t1.equals(t3) and t3.equals(t3).  The latter case is obvious enough, and with the former case, even though t1 has a reference of type Object, it is instantiated as type Test, so dynamic binding should call the overridden form of the method.  Apparently not.  My interviewer encouraged me to run the program myself, and lo and behold, there was only a single output from the overridden method: at the line t3.equals(t3).  My question then is, why?  As I mentioned already, even though t1 is a reference of type Object (so static binding would invoke Object's equals() method), dynamic binding should take care of invoking the most specific version of the method based on the instantiated type of the reference.  What am I missing?
53255
In my spring application context file, I have something like:  &lt;util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String"&gt;     &lt;entry key="some_key" value="some value" /&gt;     &lt;entry key="some_key_2" value="some value" /&gt;    &lt;/util:map&gt;   In java class, the implementation looks like:  private Map&lt;String, String&gt; someMap = new HashMap&lt;String, String&gt;(); someMap = (HashMap&lt;String, String&gt;)getApplicationContext().getBean("someMap");   In Eclipse, I see a warning that says:  Type safety: Unchecked cast from Object to HashMap  What did I do wrong? How do I resolve the issue?
105089
I have an abstract Class Monitor.java which is subclassed by a Class EmailMonitor.java.   The method:  public abstract List&lt;? extends MonitorAccount&gt; performMonitor(List&lt;? extends MonitorAccount&gt; accounts)   is defined in Monitor.java and must be overridden in EmailMonitor.java.  I currently have the method overridden in EmailMonitor.java as follows:  @Override public List&lt;EmailAccount&gt; performMonitor(List&lt;EmailAccount&gt; emailAccounts) {     //...unrelated logic     return emailAccounts; }   However, this produces the compile time error:   Name clash: The method performMonitor(List&lt;EmailAccount&gt;) of type EmailMonitor has the same erasure as performMonitor(Lis&lt;? extends MonitorAccount&gt; emailAccounts) of type Monitor but does not override it  EmailAccount is a subclass of MonitorAccount, so (in my mind at least) overriding it in this way makes perfect sense. Seeing as the compiler is not happy with my logic though, How should I go about this correctly while still keeping my compile time checks to make sure that all calls to EmailMonitor.performMonitor() receive Lists of EmailAccount rather than some other type of MonitorAccount?
5329
I'm building a function to extend the Enum.Parse concept that  Allows a default value to be parsed in case that an Enum value is not found Is case insensitive  So I wrote the following: public static T GetEnumFromString&lt;T&gt;(string value, T defaultValue) where T : Enum {     if (string.IsNullOrEmpty(value)) return defaultValue;     foreach (T item in Enum.GetValues(typeof(T)))     {         if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;     }     return defaultValue; }  I am getting a Error Constraint cannot be special class System.Enum. Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code. EDIT All suggestions below have been greatly appreciated, thanks. Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML) public static class EnumUtils {     public static T ParseEnum&lt;T&gt;(string value, T defaultValue) where T : struct, IConvertible     {         if (!typeof(T).IsEnum) throw new ArgumentException(&quot;T must be an enumerated type&quot;);         if (string.IsNullOrEmpty(value)) return defaultValue;          foreach (T item in Enum.GetValues(typeof(T)))         {             if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;         }         return defaultValue;     } }  EDIT: (16th Feb 2015) Christopher Currens has posted  below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page. EDIT 2: (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)
16584
would report a violation for:  ArrayList&lt;Object&gt; list = new ArrayList&lt;Object&gt;();   The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead".  The following line would correct the violation:  List&lt;Object&gt; list = new ArrayList&lt;Object&gt;();   Why should the latter with List be used instead of ArrayList?
103793
I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1:  T createDefault() {     if(typeof(T).IsValueType)     {         return default(T);     }     else     {         return Activator.CreateInstance&lt;T&gt;();     } }   Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is:  T createDefault() {     if(typeof(T).IsValueType || typeof(T).FullName == "System.String")     {         return default(T);     }     else     {         return Activator.CreateInstance&lt;T&gt;();     } }   But this feels like a kludge. Is there a nicer way to handle the string case?
80312
In C# 3.0 you can create anonymous class with the following syntax  var o = new { Id = 1, Name = "Foo" };   Is there a way to add these anonymous class to a generic list?  Example:  var o = new { Id = 1, Name = "Foo" }; var o1 = new { Id = 2, Name = "Bar" };  List&lt;var&gt; list = new List&lt;var&gt;(); list.Add(o); list.Add(o1);   Another Example:  List&lt;var&gt; list = new List&lt;var&gt;();  while (....) {     ....     list.Add(new {Id = x, Name = y});     .... }
86715
I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is  if you want to look at all of the code.  Here are the important parts:  private RpcMap map;  public &lt;X&gt; X get(String property) {   if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) {     return (X)NestedModelUtil.getNestedValue(this, property);   }   return map == null ? null : (X) map.get(property); }   X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the &lt;X&gt; in the public method signature.  I've tried to call this method with the following two examples to see what happens:  public Date getExpiredate() {     return  get("expiredate"); }  public String getSubject() {     return  get("subject"); }   They compile and show no errors or warnings.  I would think at the very least I would have to do a cast to get this to work.  Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime?  This seems counter to what generics are supposed to do.  Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better?  I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.