casting

  • Thread starter Thread starter juli jul
  • Start date Start date
J

juli jul

Hello,
O have a parent class and a child class with an additional functionality
(I have a property which is in a child class and isn't part of parent
class) .
How can I do a DOWNCASTING?
Thank you!
 
juli said:
Hello,
O have a parent class and a child class with an additional
functionality (I have a property which is in a child class and isn't
part of parent class) .
How can I do a DOWNCASTING?
Thank you!

class Base{}

class Child : Base
{
public void Stuff(){}
}


base b = new Child();
Child c = b as Child; // downcast
if (c != null) c.Stuff();

Richard
 
If the object reference is to an instance of the Child class then it
can be something like this (watch for typos):

Parent p = new Child();
(Child) p.PropertyOfChild = "...";

If the object reference is to an instance of the Parent class, then you
cannot cast it to the child:

//This is not allowed
Parent p = new Parent();
(Child) p.PropertyOfChild = "..." //Error! p is not a Child

Can you give a little more detail about what you are trying to do?
 
Richard Grimes said:
class Base{}

class Child : Base
{
public void Stuff(){}
}


base b = new Child();
Child c = b as Child; // downcast
if (c != null) c.Stuff();

Or:

((Child)b).Stuff();
if it is a logic error for b not to be an instance of Child.

If it isn't, you'll get an exception. If that's an error case, I prefer
to see the exception at cast line rather than either ignoring it or
getting a NullReferenceException. If it's valid for b not to be an
instance of Child, Richard's solution is the right one.
 
Back
Top