Up casting - c#
Solution 1
This type of cast is wrong, because you can't cast parents to their children.
Type of a
doesn't know about metainformation of type b
. So you need provide the explicit cast operator to do such things, but in this case you must remove inheritance.
Other option is to define some interface, such as in other questions.
More information:
http://msdn.microsoft.com/en-us/library/ms173105.aspx
http://msdn.microsoft.com/en-us/library/85w54y0a.aspx
Solution 2
Not possible. Even if you think you have it, the compiler will complain.
This usually indicates a design or logical error.
Solution 3
This is something that has always bothered me as well. I worked out a solution to it by creating my own Up-Casting utility.
You can read my article here on how to do it -- it's pretty simple actually.
http://sympletech.com/c-up-casting-utility/
Solution 4
You can't make that cast.
You can, and I guess you should, use an interface.
public interface ia
{
string x1 { get; set; }
string x2 { get; set; }
string x3 { get; set; }
}
public class a : ia
{
public string x1 { get; set; }
public string x2 { get; set; }
public string x3 { get; set; }
}
public class b : a, ia
{
}
Then you can
ia foo = new a();
Solution 5
Actually, your idea of creating a new instance of b and copying a's field values to it seems like an interesting approach. using reflection to achieve this should fit the bill nicely.
Something like: iterate through all of a's fields, get their values as stored in a and store them in the same field in b.
Still, this is not "downcasting" -- since it means a completely different object is created -- as opposed to reinterpreting the meaning of an existing object.
Related videos on Youtube
Comments
-
maxp almost 2 years
public class a{ public string x1 {get;set;} public string x2 {get;set;} public string x3 {get;set;} } public class b:a{ }
Obviously
var foo = (b)new a();
will throw a casting error at runtime.The only other way I can think to assign all the properties of an already instantiated and populated
a
is to manually copy each one over into a fresh instance ofb
.Is this correct?
-
Konrad Rudolph almost 13 years@leppie No. Not according to common terminology, at least. See Wikipedia: Downcasting and Java glossary: upcasting.
-
-
leppie almost 13 yearsYou are not allow to upcast via an explicit operator. The compiler will complain.
-
leppie almost 13 years@maxp: When 'you have it', implied creating a explicit cast operator, this WILL fail to compile.
-
leppie almost 13 years@VMAtm: 2 unrelated types are fine. But try a parent and child type. KABOOM!
-
Ben Voigt almost 13 yearsNeither upcasting nor downcasting uses a user-defined conversion.