Could anyone please explain the meaning \"this\" in C#?
Such as:
// complex.cs
using System;
public struct Complex
{
public int real;
public
Nate and d_r_w have the answer. I just want to add that in your code specifically the this. does in deed refere to the member of the CLASS to distinguish from the arguments to the FUNCTION. So, the line
this.real = real
means assign the value of the function (in this case, constructor) parameter 'real' to the class member 'real'. In general you'd use case as well to make the distinction clearer:
public struct Complex
{
public int Real;
public int Imaginary;
public Complex(int real, int imaginary)
{
this.Real = real;
this.Imaginary = imaginary;
}
}
As most answers are mentioning " the current instance of a class", the word "instance" may be difficult for newbies to understand. "the current instance of a class" means the this.varible is specifically used in the class where it is defined, not anywhere else. Therefore, if the variable name also showed up outside of the class, the developer doesn't need to worry about conflicts/confusions brought by using the same variable name multiple times.