8

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.

bluee
  • 997
  • 8
  • 18
  • 3
    SLaks answered your question good. I'm just noting to you that you misused the word `anonymous` here, which means something different. In your case, T is generic. – SimpleVar May 03 '12 at 14:05
  • Is this your API call or some third party API? If it is yours then consider changing it, because generics don't solve problem but create it in this case. – empi May 03 '12 at 14:06
  • 1
    possible duplicate of [Calling generic method with a type argument known only at execution time](http://stackoverflow.com/questions/325156/calling-generic-method-with-a-type-argument-known-only-at-execution-time) – user7116 May 03 '12 at 14:10
  • The idea is - I want to call SomeMethod - and usually I would call it like SomeMethod(); but I only know as a string that the class I want to use is "Class1" or some other class. – bluee May 07 '12 at 10:16

2 Answers2

8

You need to call it using reflection:

var method = typeof(SomeClass).GetMethod("SomeMethod");
method.MakeGenericMethod(someType).Invoke(...);
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • It's not about calling an unknown method but its the parameter I dont know until runtime. Eg. if it's Class1 or Class2, etc.. – bluee May 07 '12 at 10:14
  • SLaks and sixlettervariables got me in the right direction. Thanks guys! – bluee May 08 '12 at 10:59
4

You can make use of dynamic keyword in C# 4. You require .NET 4.0 or above as well.:

SomeMethod((dynamic)obj);

The runtime infers the actual type argument and makes the call. It fails if obj is null since then there is no type information left. null in C# has no type.

nawfal
  • 70,104
  • 56
  • 326
  • 368