C# generic methods, type parameters in new() constructor constraint

Not really; C# only supports no-args constructor constraints. The workaround I use for generic arg constructors is to specify the constructor as a delegate: public T MyGenericMethod<T>(MyClass c, Func<MyClass, T> ctor) { // … T newTObj = ctor(c); // … } then when calling: MyClass c = new MyClass(); MyGenericMethod<OtherClass>(c, co => new OtherClass(co));

Java generics: wildcard vs type parameter?

Your approach of using a generic method is strictly more powerful than a version with wildcards, so yes, your approach is possible, too. However, the tutorial does not state that using a wildcard is the only possible solution, so the tutorial is also correct. What you gain with the wildcard in comparison to the generic … Read more

Why it is not possible to define generic indexers in .NET?

Here’s a place where this would be useful. Say you have a strongly-typed OptionKey<T> for declaring options. public static class DefaultOptions { public static OptionKey<bool> SomeBooleanOption { get; } public static OptionKey<int> SomeIntegerOption { get; } } Where options are exposed through the IOptions interface: public interface IOptions { /* since options have a default … Read more

Initializing a Generic variable from a C# Type Variable

What you mean by this part is possible: new AnimalContext<a.GetType()>(); Obviously that exact syntax is wrong, and we’ll get to that, but it is possible to construct an instance of a generic type at runtime when you don’t know the type parameters until runtime. What you mean by this part is not: AnimalContext<a.GetType()> a_Context That … Read more

Why a generic can’t be assigned to another even if their type arguments can?

Instantiating a generic type with different type arguments produces two new different named types. Note that every time you supply a type argument, including in function arguments or return types, you are instantiating the generic type: // Props is instantiated with type argument ‘Generic’ func Problem() Props[Generic] { return ExampleProps } Therefore Props[Example] is just … Read more

Java generics, Unbound wildcards vs

There are two separate issues here. A List<Object> can in fact take any object as you say. A List<Number> can take at least Number objects, or of course any subclasses, like Integer. However a method like this: public void print(List<Number> list); will actually only take a List which is exactly List<Number>. It will not take … Read more