Reputation: 3266
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?
Upvotes: 2
Views: 15109
Reputation: 1708
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.
Upvotes: 3
Reputation: 8564
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.
Upvotes: 4