C # Common Interface

I need to pass the generic parameter type to the interface. I have a string with a type name.

I have something like this:

string type = "ClassType"; Type t = Type.GetType("ClassType"); IProvider<t> provider = (IProvider<t>)someObject; 

This does not work for me. What is the right way to do this? Thanks.

+4
source share
4 answers

What you are trying to do is not realistic in C # (and CLR) versions of generics. When specifying a common parameter, it should be ...

  • A specific type of code
  • Another common parameter

This information should be linked in assembly metadata. Thus, it is not possible to express a type name from a string in metadata.

You can bind a generic name at run time based on string names, but this requires reflection.

+8
source

I believe this is what you are looking for => Type.MakeGenericType

+4
source

Here is an example using reflection to load a generic type.

 using System; namespace GenericCastRuntime { class Program { static void Main(string[] args) { string type = "GenericCastRuntime.Program+Provider`1"; Type t = Type.GetType(type); string genericType = "System.String"; Type gt = Type.GetType(genericType); var objType = t.MakeGenericType(gt); var ci = objType.GetConstructor(Type.EmptyTypes); var obj = ci.Invoke(null); IProvider provider = obj as IProvider; } public class Provider<T> : IProvider<T> { public T Value { get; set; } object IProvider.Value { get { return this.Value; } set { if (!(value is T)) throw new InvalidCastException(); this.Value = (T)value; } } } public interface IProvider { object Value { get; set; } } public interface IProvider<T> : IProvider { T Value { get; set; } } } } 
+1
source

Here is a simple example:

  public static object DynamicallyCreateGeneric(Type GenericTypeSource, Type SpecificTypeSource) { System.Type SpecificType = GenericTypeSource.MakeGenericType( new System.Type[] { SpecificTypeSource } ); return Activator.CreateInstance(SpecificType); } 

... then for example:

  string type = "System.String"; Type t = Type.GetType(type); var DynamicallyCreatedGeneric = DynamicallyCreateGeneric(typeof(List<>), t); System.Diagnostics.Debugger.Break(); 

Adapt to suit your implementation and try. Of course, this method is not ideal. One of the best parts of generics is type compiler level type security.

0
source

All Articles