Reputation: 34895
Inside my .NET classes I access my properties and members through this
. What is the difference if I access them without using this
.
public class Test
{
private string _test;
public Test()
{
this.Test = "test";
// vs.
Test = "test";
// and
this._test = "test";
// vs.
_test = "test";
}
public string Test { get; set; }
}
Upvotes: 3
Views: 83
Reputation: 98740
There's no difference for the compiler. Use which is more readable for you.
public class Test
{
private string _test;
public Test(string Test)
{
this.Test = "test";
// vs.
Test = "test";
// and
this._test = "test";
// vs.
_test = "test";
}
public string Test { get; set; }
}
Upvotes: 0
Reputation: 241
Check out the msdn page: http://msdn.microsoft.com/en-us/library/dk1507sz(v=vs.80).aspx
In C# this
is primarily used to increase readability when you have variables and parameters with the same name.
Upvotes: 0
Reputation: 6778
This
is just referring to the class's variable. It saves you from being tripped up when you try:
private string Test;
public Test(String Test)
{
this.Test = Test;
// vs.
Test = Test;
}
The first one will work correctly.
Upvotes: 2
Reputation: 176896
this doent make any difference till you have parameter with same name liekt his
public class Test
{
private string _test;
public Test(string Test,string _test)
{
this.Test = "test";//this refers invoking object Test i.e class varaible
// vs.
Test = "test";//this refer method passed Test param
// and
this._test = "test";//this refers invoking object Test i.e class varaible
// vs.
_test = "test";//this refer method passed Test param
}
public string Test { get; set; }
}
so in above case method parameter Test hide class Test prameter , to avoid this you need to use this to refer current object of class
Upvotes: 1
Reputation: 25435
There is no difference, whether you use this
or not. It's just about readability.
Upvotes: 0
Reputation: 14672
There is no difference in terms of the end result.
One thing is that typing this will give you intellisense that lists only member available within that class.
Also, if the method is an extension method on the class, then you will need to use this to call it.
Upvotes: 0
Reputation: 460058
There's no difference for the compiler at all. Use whatever is more readable. I prefer using this
to show that this is a field/property instead of a local variable.
Upvotes: 2
Reputation: 6101
There is no difference in your code, but sometimes this
helps you to specify the scope.
public Test(string _test)
{
this._test = "test"; // sets class field
// vs.
_test = "test"; // sets ctor parameter
}
Upvotes: 0