Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a generic method if you only know the type parameter at runtime?

I have this method:

public List<T> SomeMethod<T>( params ) where T : new()

So I want to call this SomeMethod which is fine if I know the type:

SomeMethod<Class1>();

But if I only have Class1 at runtime I'm unable to call it?

So how to call SomeMethod with unknown T type? I got Type by using reflection.

I have the Type of type but SomeMethod<Type | GetType()> doesn't work.

Update 7. May:

Here is a sample code of what I want to achieve:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication63
{
    public class DummyClass
    {
    }

    public class Class1
    {
        public string Name;
    }

    class AssemblyTypesReflection
    {
        static void Main(string[] args)
        {
            object obj = new Class1() { Name = "John" } ;

            Assembly assembly = Assembly.GetExecutingAssembly();
            var AsmClass1 = (from i in assembly.GetTypes() where i.Name == "Class1" select i).FirstOrDefault();


            var list = SomeMethod<AsmClass1>((AsmClass1)obj); //Here it fails
        }

        static List<T> SomeMethod<T>(T obj) where T : new()
        {
            return new List<T> { obj };
        }
    }
}

This is a demo taken out of a bigger context.

like image 545
bluee Avatar asked May 03 '12 14:05

bluee


People also ask

How do you call a method of a generic type?

To call a generic method, you need to provide types that will be used during the method invocation. Those types can be passed as an instance of NType objects initialized with particular . NET types.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

How does a generic method differ from a generic type?

From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.

How do I use reflection to call a generic method?

You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod: MethodInfo method = typeof(Sample). GetMethod(nameof(Sample. GenericMethod)); MethodInfo generic = method.


1 Answers

You need to call it using reflection:

var method = typeof(SomeClass).GetMethod("SomeMethod");
method.MakeGenericMethod(someType).Invoke(...);
like image 61
SLaks Avatar answered Sep 20 '22 07:09

SLaks