Working with Dynamic C# 2.0 Generics
Yesterday I was involved in working with dynamic generic types for a project I'm working on. At least I achieved this solution to dinamically create a Generic Type for instance reading a .config file:
using System;
using System.Collections.Generic;
using System.Text;
namespace DynamicGeneric
{
class Program
{
static void Main(string[] args)
{
// "Standard" generic instantiation
GenericClass<PaoloEntity> paoloGenericClass = new GenericClass<PaoloEntity>();
Console.WriteLine(paoloGenericClass.GetEntity());
// Create a parametric generic type instance
Type paoloEntityType = Type.GetType("DynamicGeneric.PaoloEntity, DynamicGeneric");
Type paoloGenericClassType = typeof(GenericClass<>).MakeGenericType(paoloEntityType);
Object paoloGenericClassDynamic = Activator.CreateInstance(paoloGenericClassType);
Console.WriteLine(paoloGenericClassDynamic.ToString());
GenericClass<PaoloEntity> paoloGenericClassDynamic2 = (GenericClass<PaoloEntity>)paoloGenericClassDynamic;
Console.WriteLine(paoloGenericClassDynamic2.GetEntity());
}
}
public class BaseEntity
{
private String _name;
public String Name
{
get { return(this._name); }
set { this._name = value; }
}
}
public class PaoloEntity: BaseEntity
{
public PaoloEntity()
{
this.Name = "Paolo";
}
public override string ToString()
{
return (String.Format("Entity: {0}", this.Name));
}
}
public class GenericClass<TEntity>
where TEntity : BaseEntity, new()
{
public TEntity GetEntity()
{
return (new TEntity());
}
}
}
The only last problem I'm facing on is the ability not only to create an instance but also to declare a Generic Type dinamically. I mean something like:
GenericClass<typeof(paoloGenericClassType)> paoloGenericClassDynamic = ....
Of course the above line does not compile, because the compiler needs to know the generic parameter type provided to the Generic Type called "GenericClass" (I guess). On the other side I don't want to declare my Generic Type instance as an Object ... I'd loose all the benefits of generics ..... Any idea?
Update: of course I know that I can use a base class or interface for my GenericClass, in order to have a common signature for my GetEntity method instead of having just an Object. The problem that I've in my real application (not in the snippet published here) is that my GenericClass (that in reality are many classes) have a base interface that is based on generics too... probably I'm wondering too much from my life! :-)