Recently, I was rewriting some old code, especially shrink too long functions (reduce overhead, extend readability etc..). Thereby I stumpled about something that actually works:
Class definition
public abstract class BaseClass {
public string BaseProperty { get; set; }
}
public sealed class ClassA : BaseClass {
public string PropertyA { get; set; }
}
public sealed class ClassB : BaseClass {
public string PropertyB { get; set; }
}
Execution
ClassA a = null;
ClassB b = new ClassB();
(a == null ? (BaseClass)b : a).BaseProperty = "What would Jon Skeet think about this?";
Console.WriteLine(b.BaseProperty);
Output
What would Jon Skeet think about this?
Can someone explain to me how this works? What is this sorcery? Of course I can handle both instances the same way as they share a common base class, but I'm only casting one of them to the base class and I'm doing a property assignment based on a condition. Also, is this considered as a good practice or are there any significant downsides I just can't see?