C # this.everything?

I decided to use this.variableName when accessing / int strings, etc. to the fields. Will include an ArrayList, ListBox, etc. Also? How:

private ListBox usersListBox;
private void PopulateListBox()
{
  this.usersListBox.Items.Add(...);
}

... Or not?

What about classes?

MyClass myClass;
private void PlayWithMyClass()
{
  this.myClass = new MyClass();
  this.myClass.Name = "Bob";
}

? It looks weird to me. And I don't know if I should use this.PublicProperty or just private fields.

I'm not 100% with C # terminology, but hopefully what I said makes sense.

+3
source share
7 answers

I did something similar, but now I found that the IDEs are pretty smart to give me a visual indication that I am dealing with a member variable. I use only "this" when it is necessary to distinguish a member variable from a parameter with the same name.

+6
source

this. , , , . , # , , , .

this , , #, .

+4

- . .

, - ( - _).

public class A
{
  int a;
  public A(int a) 
  {  
    this.a = a;
  }
}
+2

, this .

, ? , , ,

+1

'this', . , , u (, userListBox, myClass ..).

.

, , , , , .

, , .

0

, . this.foo foo.

msdn :

.

The page about this contains a keyword with a lot more information.

0
source

Since it this.is implicit, you only need to use it when there is ambiguity between class variables and local variables with the same name.

The examples you give will work the way you wrote then, or like this:

private ListBox usersListBox;
private void PopulateListBox()
{
    usersListBox.Items.Add(...);
}

MyClass myClass;
private void PlayWithMyClass()
{
    myClass = new MyClass();
    myClass.Name = "Bob";
}

it is only a matter of personal preference. If you choose one over the other, try to be consistent.

0
source

Source: https://habr.com/ru/post/1712377/


All Articles