Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Method Executed with a runtime type [duplicate]

I have the following code:

 public class ClassExample {      void DoSomthing<T>(string name, T value)     {         SendToDatabase(name, value);     }      public class ParameterType     {         public readonly string Name;         public readonly Type DisplayType;         public readonly string Value;          public ParameterType(string name, Type type, string value)         {             if (string.IsNullOrEmpty(name))                 throw new ArgumentNullException("name");             if (type == null)                 throw new ArgumentNullException("type");              this.Name = name;             this.DisplayType = type;             this.Value = value;         }     }      public void GetTypes()     {         List<ParameterType> l = report.GetParameterTypes();          foreach (ParameterType p in l)         {             DoSomthing<p.DisplayType>(p.Name, (p.DisplayType)p.Value);         }      } } 

Now, I know I cannot perform DoSomething() is there any other way to use this function?

like image 649
Sarit Avatar asked Oct 22 '09 12:10

Sarit


People also ask

What is generic in runtime?

When a generic type is first constructed with a value type as a parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate locations in the MSIL. Specialized generic types are created one time for each unique value type that is used as a parameter.

Can dynamic type be used for generic?

Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.

What are generic methods in C #?

Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

Can we overload generic methods?

A generic method may be overloaded like any other method. A class can provide two or more generic methods that specify the same method name but different method parameters.


2 Answers

You can, but it involves reflection, but you can do it.

typeof(ClassExample)     .GetMethod("DoSomething")     .MakeGenericMethod(p.DisplayType)     .Invoke(this, new object[] { p.Name, p.Value }); 

This will look at the top of the containing class, get the method info, create a generic method with the appropriate type, then you can call Invoke on it.

like image 87
Chris Patterson Avatar answered Sep 29 '22 21:09

Chris Patterson


this.GetType().GetMethod("DoSomething").MakeGenericMethod(p.Value.GetType()).Invoke(this, new object[]{p.Name, p.Value}); 

Should work.

like image 39
Maximilian Mayerl Avatar answered Sep 29 '22 20:09

Maximilian Mayerl