Chrysokomas February 2016

Convert object to generic object in C#

I have a list of generic objects:

private readonly List<object> _repositories = new List<object>();

Those object are all of type either "XmlRepository<T>" or "DbRepository<T>". I also have a generic Methods that returns me the first repository of generic type argument provided:

public IRepository<T> GetRepository<T>() where T : class {...}

I do also know what type argument should return XmlRepository<T> or DbRepository<T>:

var xmlTypeVar = typeof(XmlType);
var myXmlRepo = GetRepository<xmlTypeVar>()

but I don't know how to to convert it to the correctly typed object instance...

var myConvertedXmlRepo = myXmlRepo as XmlRepository<???>

What do I have to do here? The following is not possible:

var myConvertedXmlRepo = myXmlRepo as XmlRepository<xmlTypeVar>
since I'm not allowed to provide a variable as generic type argument... This example here is somehow simplicated, so it is not possible to me to replace the type variable (xmlTypeVar) with the dedicated Type itself.

Any help is highly appreciated! Thank you very much!

Answers


Console February 2016

use reflection to create a generic type without knowing at compile time:

Type genericXmlRepositoryType= typeof(XmlRepository<>);
Type[] typeArgs = new[] { xmlTypeVar };
var generic = genericXmlRepositoryType.MakeGenericType(typeArgs);

As written in the comments, if you want to access a Method of XmlRepository<> after creating the dynamic instance, the best idea is to create a non-generic base class and call the method there:

XmlRepository repository = (XmlRepository)generic;
repository.UseTypeSpecificMethod();

Post Status

Asked in February 2016
Viewed 3,856 times
Voted 13
Answered 1 times

Search




Leave an answer