I have two classes that look something like this:
class BaseClass
{
public string Property1;
}
class ChildClass : BaseClass
{
public string Property2;
}
If I create an instance of ChildClass, and then cast up to the BaseClass and Json Serialize it, the attributes of the ChildClass show up.
ChildClass childInstance = new ChildClass() { Property1 = "1", Property2 = "2" };
BaseClass baseInstance = (BaseClass)childInstance;
Console.WriteLine(JsonConvert.SerializeObject(baseInstance, Formatting.Indented));
{
"Property2": "2",
"Property1": "1"
}
This is despite the fact that, of course, Property2 cannot be accessed from baseInstance in code.
Why is this happening and is there a nice fix?