2

Possible Duplicate:
Typecasting in C#

how do I down cast in c#?

Community
  • 1
  • 1
jgaerke
  • 29
  • 2
  • 4

3 Answers3

11

You just use the normal (cast) operator:

class HigherTypeInHierarchy {}
class LowerTypeInHierarchy : HigherTypeInHierarchy {}

var lowerTypeInHierarchy = new LowerTypeInHiearchy();

// OK downcast:
HigherTypeInHierarchy someObject = lowerTypeInHierarchy;
var okDowncast = (LowerTypeInHiearchy)someObject; // OK

Of course, for the cast to be valid, the object you try to cast must be of the type you cast to, or you will get a runtime Exception:

class AnotherLowerTypeInHierarchy : HigherTypeInHierarchy {}
var anotherLowerTypeInHierarchy = new AnotherLowerTypeInHiearchy();

// Failing downcast:
HigherTypeInHierarchy someObject = anotherLowerTypeInHierarchy;
var failedDowncast = (LowerTypeInHiearchy)someObject; // Exception!

If you just want to "try-cast" (i.e. are prepared to handle the situation where the type you attempt to downcast is not in fact of the designated type, use the as-cast instead:

var lowerTypeInHiearchyOrNULL = someObject as LowerTypeInHiearchy;

Downcasting is generally a bad idea, since it implies knowledge of the type outside the type system. Operations on higher levels in the hierarchy are supposed to work equally for all derived types (see Liskov substitution principle), yet by downcasting you state a contrary requirement that the type is in fact of a specific derived type).

Cumbayah
  • 4,415
  • 1
  • 25
  • 32
3
Class Animal {  }

Class Dog : Animal {  }

Dog dog = new Dog();
Animal animal = dog; //upcasting
Dog sameDog = (Dog)animal; //Downcasting
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Bablo
  • 906
  • 7
  • 18
1

http://igoro.com/archive/fun-with-c-generics-down-casting-to-a-generic-type/

Have a look at the URL above.

Also, think link that @Barry has posted would be my second choice for links because it is very simple example to follow.

Community
  • 1
  • 1
TheDevOpsGuru
  • 1,570
  • 5
  • 21
  • 36