1

I have a class for an object that looks like this:

public class SomeObject
{
   int SomeInt { get; set; }

   public void SomeMethod()
   {
       var SomeVar = this.SomeInt;
       var SomeVar2 = SomeInt;
   }
}

When I'm referring to a class property within a class method, does it make the code better/faster/safer if I write this.SomeInt instead of SomeInt like I do when I assign SomeVar2?

Thanks for your suggestions.

4

4 に答える 4

3

It doesn't affect the output, as the MSIL is the same.

I "might" be safer, if you don't have any variable naming convention that differs class variables from local variables.

于 2012-07-21T16:04:15.413 に答える
2

using "this." does not change how the code is generated. Thus, performance and safety is not affected. Whether or not you include "this." when you don't have to, is a matter of style. Some style guidelines suggest using "this." always on members.

于 2012-07-21T16:04:16.393 に答える
2

Some examples of times when you may need to add 'this' is when you have a local-scope variable in the same scope (which Resharper or VS, I forget which, should notify you of), like:

string name;
void SetName(string name)
{
     this.name = name;
}

Or if you're deriving a constructor from another for some reason:

public void Person(string Name, int age) : this(age)
{
}
public void Person(int age)
{
}

Otherwise, it's doesn't have any effect the compilation, but I still occasionally use it to explicitly differentiate between fields and parameters when they might be confusing, etc.

于 2012-07-21T16:11:36.453 に答える
0

It makes no difference at compile time. As few have suggested above that it makes your code more readable, but I think it just another way of accessing your class variable.

于 2012-07-23T04:05:28.713 に答える