mercredi 25 avril 2018

Convert a dynamic object to a concrete object in .NET C#

As you saw from the title, I need convert this object:

object obj = new{
                  Id = 1,
                    Name = "Patrick"
 };

To specific class instance.

To be more clear, here is an example for you guys:

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }

    }

    public class Scholar
    {
        public int UniqueId { get; set; }
        public string FullName { get; set; }

    }

I have two classes Student and Scholar. I cant figure out a way to properly write an algorithm of conversion to specific type.

In my opinion, pseudo code should look like this :

if(obj.CanBeConverted<Student>()){
   //should return this if statement

   obj = ConvertToType<Student>(o);

   // after this method obj type should change to Student
}else if(obj.CanBeConverted<Scholar>()){

   //at current example wont reach this place
  obj = ConvertToType<Scholar>(o);

  // after this method obj type should change to Scholar
}

It this possible to program in some way ?


I surfed the net and found this example : https://stackoverflow.com/a/17322347/8607147

However this solution always tries to convert / deserialize object or dynamic type to concrete object.





Aucun commentaire:

Enregistrer un commentaire