I am still far away from mastering C#, but the child in me is pushing me to continue improving my programming day by day.
When I make a WinForms application I want to change and use lot of controls pragmatically.
What I do not understand is when I need to use the this.control
keyword and when I should use just control
.
Sample:
If I want to change the text of my label I can write
mylabel.text = "Text for label"
or
this.mylabel.tex = "Text for label"
Which of these is the right way? Is there a simple explanation when to use the this
keyword when using controls in WinForms (such as datagrid, text, tables, etc.)?
Adding controls to the form is an easy task, what you need to do is drag a control from the toolbox and drop it onto the form or draw it on the form. You can drag the control around the form and you can also resize it easily.
NET Framework. The Control class implements very basic functionality required by classes that display information to the user. It handles user input through the keyboard and pointing devices.
In the main function, you could add this: Form1 c = new Form1(); c. ShowDialog(); Both methods will show your form as a dialog.
In this article For example, a Button control usually displays a caption indicating what action will be performed if the button is clicked. For all controls, you can set or return the text by using the Text property. You can change the font by using the Font property.
In this case, both of those lines are "correct". However, the use of "this" is not needed here.
One reason to use "this" is if you need to resolve an ambiguity. "this" gives you unambiguous access to the members of a class. Here's an example:
class Test
{
public void SetNumber(int number)
{
this.number = number;
}
private int number;
}
In this example, you must use "this" to refer to the class member "number" and assign to it the value in the passed in argument with the same name ("number").
Of course, it would be better to have a naming convention that prevents this. I tend to put an underscore in front of private member data (ie. _number).
It's only strictly necessary when you are diambiguating between a field/property and a local variable. Others prefer to use it in other places, but that's a style decision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With