I am trying to cast a RootClass-value with some properties to a ChildClass-value. The ChildClass object only has properties that are generated, based on the values of the root class.
using System;
class RootClass
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
}
class ChildClass : RootClass
{
public string CombinedValue => $"{PropertyA} {PropertyB}";
}
class Program {
static void Main(string[] args) {
var rootValue = new RootClass
{
PropertyA = "Value A",
PropertyB = "Value B",
};
var downCastedValue = (ChildClass)rootValue; // Throws System.InvalidCastException: Specified cast is not valid.
Console.WriteLine(downCastedValue.CombinedValue);
}
}