Vimesh Shah
Vimesh Shah

Reputation: 129

C# Reflection : Type cast method return value in specific type of object list

I have following assemble which contains following data

demo.dll

Class 1

namespace demo

public class Data
{
    public string FirstName {get; set;}
}

Class 2

namespace demo

public class Utility
{
   private List<Data> items;

   public Utility()
   {
      items = new List<Data>();
      items.add(new Data(){ FirstName = "Abc" });
   }

   public List<Data> GetItems()
   {
       return items;
   }
}

Now I want to load above demo.dll assemble using runtime and call GetItem() method.

For that I can write following code

Assembly assembly = Assembly.LoadFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ,"demo.dll"));

Type Utility= assembly.GetType("demo.Utility");
Type Data= assembly.GetType("demo.Data");

MethodInfo GetItems = Utility.GetMethod("GetItems");

object utility = Activator.CreateInstance(Utility);

object returnValue = GetItems.Invoke(utility, null);

Now I want to type cast above returnValue in List of type Data and access the FirstName property.

How can I achieve this using reflection?

Upvotes: 2

Views: 1140

Answers (1)

Dirk
Dirk

Reputation: 10958

Assuming that everything you wrote works then

object returnValue = GetItems.Invoke(utility, null);

returnValue is actually a List<Data>, but you can't cast it, because at compile time the compiler doesn't have the type information of the Data class. But since a List<T> implements IList you can cast to that and iterate over its items (IEnumerable<object> should work too).

Then you can use reflection again to access the FirstName property:

var returnValue = (IList)GetItems.Invoke(utility, null);

foreach (var item in returnValue)
{
    var type = item.GetType();
    var property = type.GetProperty("FirstName");
    var firstName = property.GetValue(item);
}

Upvotes: 3

Related Questions