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 of b
.
Is this correct?
Upcasting is converting a derived-class reference or pointer to a base-class. In other words, upcasting allows us to treat a derived type as though it were its base type. It is always allowed for public inheritance, without an explicit type cast.
Upcasting is safe casting as compare to downcasting. It allows the public inheritance that implicitly cast the reference from one class to another without an explicit typecast.
Upcasting (Generalization or Widening) is casting to a parent type in simple words casting individual type to one common type is called upcasting while downcasting (specialization or narrowing) is casting to a child type or casting common type to individual type.
Downcasting is useful when the type of the value referenced by the Parent variable is known and often is used when passing a value as a parameter. In the below example, the method objectToString takes an Object parameter which is assumed to be of type String.
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
Not possible. Even if you think you have it, the compiler will complain.
This usually indicates a design or logical error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With