When to use THIS keyword when working with controls on form in C#
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 thethis.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.)?
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.
精彩评论