I just ran into a problem that seems like it shouldn't be a problem, though I'm sure there's a perfectly obscure and valid reason it is. Consider the following:
public class MyBase{ // ...}public class MyChild : MyBase{ // ...}public class Foo{ public static void Bar() { MyBase base = GetMyBaseFromSomewhere(); MyChild child = (MyChild)base; }}
The last line in Bar throws a System.InvalidCastException: Specified cast is not valid. Why? It seems to me that since we're guaranteed that MyChild has everything that MyBase has, it should become the child type lacking values only for the new fields that MyChild has defined.
I'm sure there's some completely reasonable computer sciency reason this doesn't work, such as the data is stored on the heap in a structure defined as MyBase that has no knowledge of MyChild, so it can't possibly know how to become MyChild; all the same, I think it should work. If there is a way to work around this, I'd appreciate knowing about it.
Looks like this is another place where generics could certainly save the day. We could specify GetMyBaseFromSomewhere<T>() where T: MyBase, new(), and then we could tell it (in the case above) that we want a MyChild instance.
Unfortunately, this app is in 1.1, so that's not an option. As I see it, the only alternative here would be for me to define a new method like FillMyBaseFromSomewhere(MyBase base), pass a MyChild instance in, and have it populate the MyBase members on MyChild. Or (worse), I could define a MergeFromBase method that manually copies the fields from MyBase to MyChild. Am I missing other alternatives? Maybe serializing as MyBase and deserializing as MyChild would work? Anyone?
Disclaimer The opinions expressed herein are solely my own personal opinions, founded or unfounded, rational or not, and you can quote me on that.
Thanks to the good folks at dasBlog!
Copyright © 2010 J. Ambrose Little