Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Up casting - c#

Tags:

c#

.net

casting

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?

like image 342
maxp Avatar asked Jun 14 '11 12:06

maxp


People also ask

What is up casting in C++?

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.

Is Upcasting safe in C++?

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.

What is up and down casting?

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.

What is downcasting and when it is required?

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.


2 Answers

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

like image 118
VMAtm Avatar answered Oct 05 '22 06:10

VMAtm


Not possible. Even if you think you have it, the compiler will complain.

This usually indicates a design or logical error.

like image 32
leppie Avatar answered Oct 05 '22 05:10

leppie