Java Generic with ArrayList

ArrayList<? extends A> means an ArrayList of some unknown type that extends A. That type might not be C, so you can’t add a C to the ArrayList. In fact, since you don’t know what the ArrayList is supposed to contain, you can’t add anything to the ArrayList. If you want an ArrayList that can … Read more

How does Java’s use-site variance compare to C#’s declaration site variance?

I am just going to answer the differences between declaration-site and use-site variance, since, while C# and Java generics differ in many other ways, those differences are mostly orthogonal to variance. First off, if I remember correctly use-site variance is strictly more powerful than declaration-site variance (although at the cost of concision), or at least … Read more

Why can’t I catch a generic exception in C#?

Bizarre behavior here… VS2k8 console app. The following: try { throw new T(); } catch (T tex) { Console.WriteLine(“Caught passed in exception type”); } catch (Exception ex) { Console.WriteLine(“Caught general exception”); } results in “Caught general exception”. But, remove the (useless) variables from the catch statements: try { throw new T(); } catch (T) { … Read more

How to use Activator to create an instance of a generic Type and casting it back to that type?

Since the actual type T is available to you only through reflection, you would need to access methods of Store<T> through reflection as well: Type constructedType = classType.MakeGenericType(typeParams); object x = Activator.CreateInstance(constructedType, new object[] { someParameter }); var method = constructedType.GetMethod(“MyMethodTakingT”); var res = method.Invoke(x, new object[] {someObjectThatImplementsStorable}); EDIT You could also define an additional … Read more