Skip to content

Instantly share code, notes, and snippets.

@callerobertsson
Last active August 19, 2016 08:48
Show Gist options
  • Save callerobertsson/989ded86ee35d1adaf06 to your computer and use it in GitHub Desktop.
Save callerobertsson/989ded86ee35d1adaf06 to your computer and use it in GitHub Desktop.
C#: True down cast from child to parent using JSON
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace DownCaster
{
static class Program
{
static void Main()
{
var child = new Child
{
InParentAndChild = "foo",
OnlyInChild = "bar",
Items = new List<SubItem>
{
new SubItem
{
InItemAndItemChild = "fuz",
OnlyInSubItem = "baz"
}
}
};
Console.WriteLine("Child: " + JsonConvert.SerializeObject(child));
var parent = child.DowncastToBase();
Console.WriteLine("Parent: " + JsonConvert.SerializeObject(parent));
Console.ReadLine();
}
}
public class Parent
{
public string InParentAndChild { get; set; }
public IList<Item> Items { get; set; }
}
public class Child : Parent
{
public string OnlyInChild { get; set; }
public new IList<SubItem> Items { get; set; }
}
public class Item
{
public string InItemAndItemChild { get; set; }
}
public class SubItem : Item
{
public string OnlyInSubItem { get; set; }
}
public static class DowncastExtensions
{
public static Parent DowncastToBase(this Child c)
{
var json = JsonConvert.SerializeObject(c);
var parent = JsonConvert.DeserializeObject<Parent>(json);
parent.Items = c.Items.Select(i => i.DowncastToBase()).ToList();
return parent;
}
public static Item DowncastToBase(this SubItem si)
{
var json = JsonConvert.SerializeObject(si);
return JsonConvert.DeserializeObject<Item>(json);
}
}
}
@Fijo
Copy link

Fijo commented Aug 19, 2016

this is very slow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment