See i have a situation like this…
object myRoledata = List<Roles>() --> (some list or Ienumerable type)
Now i have a generic method which creates an XML object from List<T> –
Something like this..
public string GetXML<T>(object listdata)
{
List<T> objLists = (List<T>)Convert.ChangeType(listData, typeof(List<T>));
foreach(var obj in listdata)
{
//logic to create xml
}
}
Now in order to run this method I have to do like this:
string xml = GetXML<Roles>(myRoledata);
Now i dont know what Type may come to me to be passed to GetXML method. I have a method which will call GetXML for different Types e.g. Roles, Users etc
now i can get the Type within the List<> like this
Type genericType = obj.GetType().GetGenericArguments()[0];
but cannot pass it like this
string xml = GetXML<genericType>(myRoledata);
Is there anyway in which i can pass any genericTypes to GetXML method?
This is a problem you probably want to avoid solving. It is possible, via reflection, to call methods dynamically without statically resolving them – but it kind of defeats the whole point of the type-annotations.
Either do this:
… which you now can call with any
IEnumerable, or write it the “modern” way as:… which you can call with any
IEnumerableviaGetXML(someEnumerable.Cast<object>())and in C# 4.0 even directly by covariance.If you need the type of an element runtime, you can get it using
.GetType()on each element, or you can just pass it in as a parameter (and provide an override for backwards-compatibility):Incidentally, if you’re constructing XML, a string is probably a less robust return-type choice: if possible, you could work with something like an
XElementinstead – and get xml-validity guarantee’s to boot.