The following program works correctly. However, I would like to change it to not use InvokeMember. I would like to be able to cast the return value from CreateInstance into GenericBase and call the Foo method directly. In this code sample I know that the type is Derived. However, in my actual code, all I know is that the type is derived from GenericBase. All my attempts to cast an object into a GenericBase fail to compile. C# insists that I supply the type parameter when I use GenericType in a cast.
Is this possible?
using System;
using System.Collections.Generic;
using System.Text;
namespace GenericTest
{
class Program
{
static void Main(string[] args)
{
Type t = typeof(Derived);
object o = Activator.CreateInstance(t);
t.InvokeMember("Foo", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] { "Bar" });
}
}
class GenericBase<T>
{
public void Foo(string s)
{
Console.WriteLine(s);
}
}
class Derived : GenericBase<int>
{
}
}