Translate

Friday, December 21, 2012

c# cast parent to child (c# downcast)

The Principle:

The easiest way to downcast in C# is to serialize the parent and then de-serialize it into a child instance.


 var serializedParent = JsonConvert.SerializeObject(parentInstance); 
 Child c  = JsonConvert.DeserializeObject<Child>(serializedParent );



The complete example :

For the console application example below I used  Newtonsoft.Json to serialize  an abject into a JSON object. If you are using asp.net, a reference to  Newtonsoft.Json is automatically included when you create a new project.



using System; 
using Newtonsoft.Json;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new Animal { AnimalProperty = "I am an animal" }; 
 
            //Dog d = (Dog)a; //throws  System.InvalidCastException
 
 
            var serializedAnimal = JsonConvert.SerializeObject(a); 
            Dog d  = JsonConvert.DeserializeObject<Dog>(serializedAnimal);
 
            d.DogProperty = "woof woof";
 
            Console.WriteLine(d.AnimalProperty);//Displays I am an animal
            Console.WriteLine(d.DogProperty);   //Displays woof woof
 
        }
    }
 
    public class Animal
    {
       
 
        public string AnimalProperty
        {
            get; 
            set; 
        }
    }
 
    public class Dog : Animal
    {
 
        public string DogProperty
        {
            get;
            set;
        }
    }
 
 
}

2 comments:

  1. What if you're NOT using ASP.net? What if you're in a WinForms C# app? What if you have the data in an object converted from XML to proxy classes in Reference.cs?

    ReplyDelete
  2. This article doesn't have anything to do with ASP.NET explicitly. It just shows that you can downcast from a parent class object to a child class object by serialize the parent class object into JSON, then deserialize the JSON string into the child class object.

    I'm not sure if XML allows deserialization of XML to C# object if the attributes are not perfectly match, though.

    ReplyDelete

Comments will appear once they have been approved by the moderator