Tuesday, June 13, 2017

pseudocontravariance via serialization!

If we can make C# Animal objects from this...

namespace Casting.Models
{
   public class Animal
   {
      public string Name { get; set; }
   }
}

 
 

...and Cat inheirts from Animal...

namespace Casting.Models
{
   public class Cat : Animal
   {
      public int Lives { get; set; }
   }
}

 
 

Well remember how you can't upcast a list of children to a list of parents in C#. I found a way. Look!

using System.Collections.Generic;
using System.Web.Mvc;
using Casting.Models;
using Newtonsoft.Json;
namespace Casting.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         List<Cat> cats = new List<Cat>()
         {
            new Cat() { Name="Foo", Lives=9 },
            new Cat() { Name="Bar", Lives=8 },
            new Cat() { Name="Baz", Lives=7 },
            new Cat() { Name="Qux", Lives=6 }
         };
         string json = JsonConvert.SerializeObject(cats);
         List<Animal> animals = JsonConvert.DeserializeObject<List<Animal>>(json);
         return View(animals);
      }
   }
}

 
 

We may, yes, downcast the other way around. Not only does the code above not break but the code below does not break either. The Lives getsetter just gets lost above and below it become zero for every Cat.

using System.Collections.Generic;
using System.Web.Mvc;
using Casting.Models;
using Newtonsoft.Json;
namespace Casting.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         List<Animal> animals = new List<Animal>()
         {
            new Animal() { Name="Foo" },
            new Animal() { Name="Bar" },
            new Animal() { Name="Baz" },
            new Animal() { Name="Qux" }
         };
         string json = JsonConvert.SerializeObject(animals);
         List<Cat> cats = JsonConvert.DeserializeObject<List<Cat>>(json);
         return View(cats);
      }
   }
}

 
 

What's not to like? Well, this does not make for polymorphic behavior as the Cats that become Animals do not retain any of their cattiness. What is to like? Fake contravariance!

No comments:

Post a Comment