Calling property from derived class

kdf123

New member
Joined
Dec 25, 2021
Messages
4
Programming Experience
Beginner
In one of the examples I was going through I noticed that you can call in a "Form1 : Form" derived class, property 'Visible' of the .NET class Control without creating an instance of the Control class first. i.e. It is called directly
If (Visible) { ... }

How is this possible?
 
A form is a control because it inherit from it, thus inherit the members. Accessing the member without qualifying it means current instance, for example this.Visible.
Try this for fun in a form:
C#:
var isControlType = this is Control;
 
Your Form1 class inherits Form, as you showed. You should read the documentation for that Form class. Just click it in code and press F1. Amongst other things, the documentation for a type will provide the inheritance hierarchy, so you will see the chain of types trough which Form inherits Control. You will also see a list of all the members, both inherited and directly declared in that type.
 
Both Form and Control are in the System.Windows.Forms namespace.
So Form is not inheriting from Control.
Also does that mean that you can call an inherited member without the 'this" keyword?
Is the 'this' keyword only used to override inherited members?
 
Last edited:
this refers to the current object. If you only it then it is implied if the current object has a member with the name you use. You generally only have to use it when there is a local variable with the same name. A common such scenario is a constructor with a parameter that gets assigned to a field or property with the same name.
 
So if I have declared a property in my class with the name 'Visible' , I can call it with the 'this' keyword. But if I dont have a property of the name 'Visible' I can call the inherited property without the 'this' keyword.
But Form does not inherit from Control. So why don't I have to create an instance of Control before using its 'Visible' property in my Form1 class?

Even in the example in the link, the 'hScrollBar1' and 'vScrollBar1' instances are created before calling 'Visible'
Control.Visible Property

In this link also it is clear that Form is not derived from Control
Control Class Definition
 
Last edited:
Docs make it quite clear it is: Form Class (System.Windows.Forms)

1640510569314.png


If you use this intellisense will most often suggest to simplify the expression by removing it.
 
Back
Top Bottom