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;
        }
    }
 
 
}

1 comment:

  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

Comments will appear once they have been approved by the moderator