1

how to create a generic method for something like this

Type myType = Type.GetType(classNameType.AssemblyQualifiedName);  --gets the required type

CustomerWrapper.DeserializeJsonFromStream<myType>(stream); -- failing here

I would like to pass diiferent types at the above line but getting error saying "myType is variable but used as type". How can I resolve this.?

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
Ravio
  • 115
  • 9
  • 1
    I don't know what `DeserializeJsonFromStream` method looks like, but sometimes they have a overloaded version of the same method that should look like `DeserializeJsonFromStream(Stream stream, Type ofType)`. Do you see anything like that? – Andy Jul 31 '20 at 03:15

1 Answers1

3

You can't do this out-of-the-box. Generics needs to be known at compile time so the compiler can generate the appropriate IL and generated classes.

However you can use reflection with a bit of tomfoolery (given the usual reflection performance hit). Here is an overly contrived example

Given

public class CustomerWrapper
{
   public void DeserializeJsonFromStream<T>(Stream stream)
     => Console.WriteLine(typeof(T).Name);
}

Usage

var wrapper = new CustomerWrapper();
var stream = new MemoryStream();

var myType = typeof(string);

var method = typeof(CustomerWrapper).GetMethod(nameof(CustomerWrapper.DeserializeJsonFromStream));

if (method == null) 
   throw new MissingMethodException(nameof(CustomerWrapper),nameof(CustomerWrapper.DeserializeJsonFromStream));

var genericType = method.MakeGenericMethod(myType);
genericType.Invoke(wrapper, new object[]{stream});

Output

String

Or if you feel lucky and like everything on the one line

var method = typeof(CustomerWrapper)
    .GetMethod(nameof(CustomerWrapper.DeserializeJsonFromStream))
    .MakeGenericMethod(myType)
    .Invoke(wrapper, new object[] {stream});

Note : it's worth pointing out there is usually a type parameter in most deserialization methods Deserialize(String, Type, JsonSerializerOptions) as such you are likely better to use them.


Additional Resources

Type.GetMethod Method

Gets a specific method of the current Type.

MethodInfo.MakeGenericMethod(Type[]) Method

Substitutes the elements of an array of types for the type parameters of the current generic method definition, and returns a MethodInfo object representing the resulting constructed method.

MethodBase.Invoke Method

Invokes the method or constructor reflected by this MethodInfo instance.

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141