+ 2
"this" in C#
I'm struggling to comprehend what does the "this" exactly do in C#. I thought it's only used to call an "object" of a class, inside the same class without the need of earlier introduction. But it seems that it's further than that, so what does it really do? Any help/explanation would be welcomed.
13 ответов
+ 4
public Fraction(Fraction original) : this(original.num,original.den)
{
}
The first constructor is not called in the body of the method but in the method definition
There is a : missing
public Fraction //method name
(Fraction original) //parameters
: //use anonther constructor
this(original.num,original.den) //parameters of the other constructor
{ //body second constructor
}
It is called constructor chaining
+ 7
@sneeze
It can point to anything within the current instance of the Object.
+ 6
It refers to the current Object.
Example/
public ClassName getClassInstance(){
return this; // returning this object
}
You can use it to return or pass the current instance.
To call the current instances constructors or members.
To differentiate between instance variables and local variables.
To reassign a struct value.
Ex/
this = new StructName();
And probably many more. The main idea is that it's just talking about the current instance of the class.
So, if I do something like this:
Animal a = new Animal();
Animal b = a;
bool c = a.isEqual(b);
Then in the Animal class I could have:
public bool isEqual(Animal anim){
return this == anim;
}
Here I'm just saying 'is the reference of this object equal to the one I passed in the parameters'.
If we look back at when we called the method:
a.isEqual(b);
We used an instance of a to call the method, so 'this' refers to the Animal a.
The method will return true.
+ 2
In a constructor.
Consider a class Fraction that has in it's field 2 integers: num, den;
First constructor:
public Fraction(int n, int d)
{
num=n; den=d;
}
Second constructor:
public Fraction(Fraction original)
{
this(original.num,original.den);
}
+ 2
So this in your example points to the first constructor. this can not only point to variables but also to methods.
+ 1
Your thought is totally correct. this does not do anything more.
Where have seen this being used in a place you did not expect?
0
@Rrestoring faith That is true.
0
Okay thanks guys.
@sneeze @Restoring faith
0
Guys... I tried my snippet of code that i posted in the comments, it returned an error for using "this". It said: Method Name Expected....
Why? Shouldn't it work ???
0
Are you missing a dot behind this ?
also should it be
this.Fraction (...);
0
Tried them both... Neither one worked
0
Thanks! Finally the answer... but could you explain why?
0
see the update in previous post