Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic interface

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

I have something like this:

string type = "ClassType";
Type t = Type.GetType("ClassType");

IProvider<t> provider = (IProvider<t>)someObject;

This doesn't work for me. What is the correct way to do it? Thanks.

like image 601
Crios Avatar asked Dec 14 '22 03:12

Crios


2 Answers

What' you're trying to do is not really possible in the C# (and CLR) version of generics. When specifying a generic parameter it must be either ...

  • A Concrete type in code
  • Another generic parameter

This information must be bound in the metadata of the assembly. There is no way to express a type name from string in metadata in this fashion.

It is possible to bind a generic at runtime based on string names but this requires reflection.

like image 100
JaredPar Avatar answered Jan 02 '23 14:01

JaredPar


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

like image 21
Arnis Lapsa Avatar answered Jan 02 '23 13:01

Arnis Lapsa