frenchie
frenchie

Reputation: 51997

c# is adding "this" optional within a class method

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.

Upvotes: 1

Views: 160

Answers (4)

Dee
Dee

Reputation: 436

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.

Upvotes: 0

K893824
K893824

Reputation: 1319

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.

Upvotes: 2

Peter Ritchie
Peter Ritchie

Reputation: 35869

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.

Upvotes: 2

Amirshk
Amirshk

Reputation: 8258

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.

Upvotes: 3

Related Questions