-1

I have an object that implements an interface and inherits from another class. However for a function, I can only pass in an interface of the item. Is it possible to get a variable from the parent object or null if they are not there?

  public class ProductStamp
  {
   public int qty;
  }

  public class TrolleyItem : ProductStamp, ITrolleyItem
  {

  }

  private void foo(ITrolleyItem trolleyItem)
  {
     trolleyItem.qty;  

  }

Sorry for the confusing situation. I just want to know if this is possible and if so how I can best go about it.

Note: I have simplified the situation but each of these classes are in very separate places with other attachments relying on them. Due to how it is structured, I cannot simply pass in foo(TrolleyItem trolleyItem)

thank you in advance

R. Smith
  • 1
  • 1
  • You could cast is with `var ps = trolleyItem as ProductStamp;` and check if it is not null. – FCin Aug 25 '17 at 06:17
  • 1
    _"Is it possible to get a variable from the parent object"_ -- of course. But it would be a really bad idea to write code like that. If you can only pass the interface type, there should be a good reason for that. And if there is, there's a good reason the code receiving the interface object should not need to know what else the object implements. – Peter Duniho Aug 25 '17 at 06:47

1 Answers1

0

Is it possible to get a variable from the parent object or null if they are not there?

Yes, you would need to cast i, and if the cast was sucessfull you can access the variable:

private void foo(ITrolleyItem trolleyItem)
{
     TrolleyItem temp = trolleyItem as TrolleyItem   

     // this checks whether the cast has worked.
     // if true you have now a real object of type TrolleyItem and it has the parent variable
     if(temp != null)
     {
         temp.qty
     }
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76