dimanche 22 novembre 2020

Convert an Object to a user defined type class object without Reflection in C#

I have the following code where i am adding some class objects in an Array.

  Object[] ArrayOfObjects = new Object[] {typeof(Person), typeof(Company)};

Now if i want to iterate through my class items, how can i convert each item back to its original Type (such as Person and Company)? This might be possible using Reflection but i want to find out if C# has some built in functionality to achieve this.

  foreach (var item in ArrayOfObjects)
  {
     // TODO Convert item back to Original Type (Person or Company)
     // I am doing something like this but not working
     var person  =  Convert.ChangeType(item, typeof(Person));

     //I can not do this too as hardcoding the type inside the loop makes no sense
     var person = item as Person; //I need to convert item as Person or Company so that i can automate the tasks here.
  }

Much Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire