0

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);
    }
}
Anton
  • 29
  • 5
  • Have you tried using pointers to the classes involved? – JosephDoggie Apr 01 '21 at 13:15
  • 1
    This may theoretically be possible in your specific case, but it is not possible in the general case, and it is not allowed by the language. Even in your specific case (if it were possible), the cast operation would not be able to modify the underlying object, so I'm not sure what you could expect something like `((object)downCastedValue).GetType()` to return – canton7 Apr 01 '21 at 13:15
  • Why do you need the child class at all? I would just make an extension method on `RootClass` called `CombinedValue`. – Sweeper Apr 01 '21 at 13:17
  • 1
    and this is the [valid answer from that](https://stackoverflow.com/a/2820418/542251) – Liam Apr 01 '21 at 13:18

0 Answers0