2

Lets say you have 2 forms: FormA and FormB..

In FormA I have some properties. FormA creates FormB and set the owner property. for example:

public FormA() 
{
    FormB = new FormB(){Owner = this};
}

Now, in FormB if I want an access to the properties that I declared on FormA. why I can't see them when I'm Write:

Owner. // here I need to see FormA properties...

why it doesn't work like this?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Elior
  • 3,178
  • 6
  • 37
  • 67

3 Answers3

4

try this:

var forma = Owner as FormA;
forma.Stuff = otherstuff;
Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
4

You can't see because of inheritance and polymorphism.

Forms, in .NET, inherit from a base class called Form. You FormA is a class derived from Form, as is FormB.

Now, Form has a reference to an Owner form,

public Form Owner { get; }

You assigned a FormA to it. No problem! Derived classes can be treated as their base classes. But, if you access it, you get back a Form, so what you need to do is cast the new form back to the Form you actually provided:

FormA form = (FormB)Owner;

This is almost the same as doing:

FormA form = Owner as FormB;

But there are some caveats. The as operator is a "safe cast", which returns nulls if the object isn't of the provided type.

I'd recommend you just you the code we provided and, when you get the time, study Inheritance and Polymorphism. They are key to understanding what is happening.

If I may do some self-promotion, I wrote a piece on why you'd generally avoid as which you may find interesting, in time.

Bruno Brant
  • 8,226
  • 7
  • 45
  • 90
  • Jon Skeet covers `as vs cast` [here](http://stackoverflow.com/a/496167/119477). In the context of this question it depends of if Owner *should* be an instance for FormA or if it *might* be an instance of FormA. In the OP's example it looks like the *should* case but you'd need to know more about the application to know for sure. – Conrad Frix Mar 14 '13 at 22:15
  • @ConradFrix, I agree completely that it depends, and it was my opinion that the OP expected to have a FormA as the owner, since that was his problem in the first place. But I accept that it may not be the case. – Bruno Brant Mar 18 '13 at 16:53
3

The reason is a concept called polymorphism. In a more specific sense, the Owner property is of type Form. FormA inherits from type Form, so in a way, it's a Form as well as a FormA. The way you get around this is to "cast" owner as a FormA, as follows:

FormA fa = Owner as FormA;
if (fa != null)
{
    // do something
}

The reason you want to check for null here is that maybe someone else is using your FormB, and has set the Owner property to be of type FormC, which you won't necessarily be able to control. In that case, the code Owner as FormA will return null. The null check therefore ensures you don't get any nasty surprises.

Steve Westbrook
  • 1,698
  • 2
  • 20
  • 21