I'm trying to figure out a way to pass a type into a generic function by only knowing the type name.  public void Main() {     string typeName = "string";     Test&lt;typeName&gt;(); }  public void Test&lt;T&gt;() {     // Do Work }
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;()     {         //...     } }
3278
So, I understand that the following doesn't work, but why doesn't it work?  interface Adapter&lt;E&gt; {}  class Adaptulator&lt;I&gt; {     &lt;E, A extends I &amp; Adapter&lt;E&gt;&gt; void add(Class&lt;E&gt; extl, Class&lt;A&gt; intl) {         addAdapterFactory(new AdapterFactory&lt;E, A&gt;(extl, intl));     } }   The add() method gives me a compile error, "Cannot specify any additional bound Adapter&lt;E&gt; when first bound is a type parameter" (in Eclipse), or "Type parameter cannot be followed by other bounds" (in IDEA), take your pick.  Clearly you're just Not Allowed to use the type parameter I there, before the &amp;, and that's that. (And before you ask, it doesn't work if you switch 'em, because there's no guarantee that I isn't a concrete class.) But why not? I've looked through Angelika Langer's FAQ and can't find an answer.  Generally when some generics limitation seems arbitrary, it's because you've created a situation where the type system can't actually enforce correctness. But I don't see what case would break what I'm trying to do here. I'd say maybe it has something to do with method dispatch after type erasure, but there's only one add() method, so it's not like there's any ambiguity...  Can someone demonstrate the problem for me?
50233
I have built myself a generic collection class which is defined like this.   public class StatisticItemHits&lt;T&gt;{...}   This class can be used with int and string values only. However this  public class StatisticItemHits&lt;T&gt; where T : string, int {...}   won't compile. What am I doing wrong?
62286
I need to make some reflective method calls in Java. Those calls will include methods that have arguments that are primitive types (int, double, etc.). The way to specify such types when looking up the method reflectively is int.class, double.class, etc.  The challenge is that I am accepting input from an outside source that will specify the types dynamically. Therefore, I need to come up with these Class references dynamically as well. Imagine a delimited file a list of method names with lists of parameter types:  doSomething int double doSomethingElse java.lang.String boolean   If the input was something like java.lang.String, I know I could use Class.forName("java.lang.String") to that Class instance back. Is there any way to use that method, or another, to get the primitive type Classes back?  Edit: Thanks to all the respondents. It seems clear that there is no built-in way to cleanly do what I want, so I will settle for reusing the ClassUtils class from the Spring framework. It seems to contain a replacement for Class.forName() that will work with my requirements.
12313
I thought I understood Java generics pretty well, but then I came across the following in java.lang.Enum:  class Enum&lt;E extends Enum&lt;E&gt;&gt;   Could someone explain how to interpret this type parameter? Bonus points for providing other examples of where a similar type parameter could be used.
93303
If I have the following code: MyType&lt;int&gt; anInstance = new MyType&lt;int&gt;(); Type type = anInstance.GetType();  How can I find out which type argument(s) &quot;anInstance&quot; was instantiated with, by looking at the type variable? Is it possible?
124087
I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent:  t =&gt; t.SomeProperty.Contains("stringValue");   So far I have got:      private static Expression.Lambda&lt;Func&lt;string, bool&gt;&gt; GetContainsExpression&lt;T&gt;(string propertyName, string propertyValue)     {         var parameterExp = Expression.Parameter(typeof(T), "type");         var propertyExp = Expression.Property(parameter, propertyName);         var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :)         ...         return Expression.Lambda&lt;Func&lt;string, bool&gt;&gt;(containsMethodExp, parameterExp); //then something like this     }   I just don't know how to reference the String.Contains() method.  Help appreciated.
5986
Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no (due to type erasure), but I'd be interested if anyone can see something I'm missing:  class SomeContainer&lt;E&gt; {     E createContents()     {         return what???     } }   EDIT: It turns out that  could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.  I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's .
28242
I have a generic class in my project with derived classes.  public class GenericClass&lt;T&gt; : GenericInterface&lt;T&gt; { }  public class Test : GenericClass&lt;SomeType&gt; { }   Is there any way to find out if a Type object is derived from GenericClass?  t.IsSubclassOf(typeof(GenericClass&lt;&gt;))   does not work.
33470
What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading.   What is the best way to achieve this?
93253
I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.  Example:  public class MyGenericClass&lt;T&gt; {   public void doSomething() {     // Snip...     // Call to a 3rd party lib     T bean = (T)someObject.create(T.class);     // Snip...   } }   Clearly the example above doesn't work  and results in the following error: Illegal class literal for the type parameter T.  My question is: does someone know a good alternative or workaround for this?
40774
I have a VB background and I'm converting to C# for my new job.  I'm also trying to get better at .NET in general.  I've seen the keyword "T" used a lot in samples people post.  What does the "T" mean in C#?  For example:  public class SomeBase&lt;T&gt; where T : SomeBase&lt;T&gt;, new()   What does T do? Why would I want to use it?
71247
List&lt;String&gt; nameList = new List&lt;String&gt;(); DropDownList ddl = new DropDownList();   List is populated here, then sorted:  nameList.Sort();   Now I need to drop it into the dropdownlist, which is where I'm having issues (using foreach):  foreach (string name in nameList){     ddl.Items.Add(new ListItem(nameList[name].ToString())); }   No workie - any suggestions? It's giving me compile errors:  Error - The best overloaded method match for 'System.Collections.Generic.List&lt;string&gt;.this[int]' has some invalid arguments   Error - Argument '1': cannot convert from 'string' to 'int'
56847
This is an extension of .  So, using the answer from the previous question I mentioned, I am able to make a generic utility that would convert/parse an Enumeration to a String.  Now the only problem I have with my solution is, I can't seem to refactor the code to my liking. It works the way I want it to, but it is a tad more on the code heavy side than I had hoped for. I was curious if there was a design pattern (or any other way to code it) to help solve this issue. I am thinking there is a creational design pattern that will help in this case. I would be easy if I had lambda expression but, Apex is not quite there yet ;).  The code I use has kind of patterns dug into it already. It uses the Strategy, Factory, and Template(ish) pattern I believe. I have the resources to find something to solve this issue (my favorite Design Pattern books), but nothing I can think of jumps out at me.  Here is the code for my utility for just one enumeration:  private interface EnumerationToStringHelper {     List&lt;Object&gt; ProvideEnumerationValues();     Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue); }  private class ExampleEnumToStringHelper implements EnumerationToStringHelperExampleEnum {     public List&lt;Object&gt; ProvideEnumerationValues(){ return (List&lt;Object&gt;)ExampleEnum.values(); }     public Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue)     {         return  ((ExampleEnum)enumerationValue).name().equalsIgnoreCase(possibleEnumeration);     } }  private static Map&lt;Type, EnumerationToStringHelper&gt; TypeToEnumerationMap;  private static void PopulateTypeToEnumerationMap() {     TypeToEnumerationMap = new Map&lt;Type, EnumerationToStringHelper&gt;     {         Type.forName('ExampleEnum') =&gt; new ExampleEnumToStringHelper()     }; }  public static Object ConvertStringToEnumeration(Type enumerationType, String possibleEnumeration) {     if(possibleEnumeration == null) return null;     if(TypeToEnumerationMap == null)         PopulateTypeToEnumerationMap();      EnumerationToStringHelper conversionAction = TypeToEnumerationMap.get(enumerationType);      if(conversionAction == null)         throw new EnumerationToStringException('The Type you enter is either a) not an enumeration or b) not a supported enumeration.');      for(Object particalarEnumValue : conversionAction.ProvideEnumerationValues())         if(conversionAction.CompareEnumerationToString(possibleEnumeration, particalarEnumValue))             return particalarEnumValue;     return null; }   public class EnumerationToStringException extends Exception { }   Now in order to use the utility, it is exactly what I hoped for.  return (ExampleEnum)RT_GeneralUtilities.ConvertStringToEnumeration(Type.forName('ExampleEnum'), 'Testing');   It is a little long, but it beats having the entire for loop for 12 or more different Enum types. That is why I wanted to build the utility - essentially for better readability and test coverage purposes.  The downside with this is I have to make a helper for every single Enum type. So it makes it kind of an eyesore maintainability-wise.    I was hoping there was a pattern I could implement to assuage that eyesore and make it appealing on both sides. Any suggestions?
88139
I am wondering why the C# 3.0 compiler is unable to infer the type of a method when it is passed as a parameter to a generic function when it can implicitly create a delegate for the same method.  Here is an example:  class Test {     static void foo(int x) { }     static void bar&lt;T&gt;(Action&lt;T&gt; f) { }      static void test()     {         Action&lt;int&gt; f = foo; // I can do this         bar(f); // and then do this         bar(foo); // but this does not work     }    }   I would have thought that I would be able to pass foo to bar and have the compiler infer the type of Action&lt;T&gt; from the signature of the function being passed but this does not work.  However I can create an Action&lt;int&gt; from foo without casting so is there a legitimate reason that the compiler could not also do the same thing via type inference?
30163
What is the difference between this:  void MyMethod(IMyInterface value) {     //... }   and this:  void MyMethod&lt;T&gt;(T value) where T : IMyInterface {     //... }
65745
I have created an Apex InterfaceFactory that the user can use to get an instance of a specified implementation of an interface. For this I use the System.Type class. The actual name of the class can be set in a custom setting. I wanted to be able to pass some parameters to the constructor of the dynamically instantiated class. In short; this is the code I'm talking about:  public static MyInterface GetMyInterfaceImplementationByClassName(String settingName){     String implementationClassName;     Type t;     MyInterface implementation = null;      //get the actual class name from the custom setting     Interface_Implementations__c settings = Interface_Implementations__c.getInstance(settingName);      //just make sure there actually is a className found     if (settings != null &amp;&amp; settings.Class__c != null) {         implementationClassName = settings.Class__c;         //get the type object for the class name retrieved from the custom setting         t = Type.forName(implementationClassName);         //this line is where my question comes in; how can I pass parameters here         implementation = (MyInterface)t.newInstance();     }      return implementation; }