I've got a scenario that I'm hoping to find a shortcut for. I have a
base class and a derived class - the derived class adds additional
properties. For example:
public class Foo {
public int Prop1 { get; set; }
public int Prop2 { get; set; }
}
public class Bar : Foo {
public int Prop3 { get; set; }
}
Suppose I have a Foo, and want to convert it to a Bar (obviously Prop3
would be empty) - I don't care if it's a cast or a convert. I can
think of several ways of doing this:
- create a constructor in Bar that accepts a Foo, then one-by-one
assign the values of Prop1 and Prop2 to the new instance's Prop1 and
Prop2.
- create a static method ConvertToBar(Foo foo) that does the same
thing
- use reflection to retrieve the values of all properties of the Foo
and assign to a new Bar.
I can't put an explicit or implicit conversion operator in Foo,
because Bar derives from Foo, and for some reason (which I'm sure
makes a lot of sense to someone) the compiler won't let me do that.
Even if I could, I'd still have to assign the properties one at a
time.
Any ideas? I'd rather not use reflection, but that seems to be the
only way to do this using the smallest amount of code and allowing for
new properties to be added to Foo without a code change to Bar - there
are a couple dozen properties in Foo, and only one or two extra
properties in Bar, so I'm hoping there's some trick out there that
would save me from doing this.
Thanks
Joe