Whenever the keyword this
is called inside a C# class, does it return a reference to the instance that it appears in, or does it return the value of the instance (like a copy)?
For example, would the following code print the number 23 (meaning this
returned a copy of foo
), or the number 96 (meaning this
returned a reference to foo
)?
class Program
{
static void Main()
{
Foo foo = new Foo { 23 };
foo.Bar();
Console.Write(foo.FooBar);
}
}
class Foo
{
public int FooBar { get; set; }
public void Bar()
{
Foo newFoo = this;
newFoo.FooBar = 96;
}
}
Since this
relates to a reference type (class
), it returns a reference to the instance. Using this
is no different from using foo2
in the following code snippet:
var foo1 = new Foo();
var foo2 = foo1;
In the same way as foo2
only references (!) the object referenced by foo1
, inside of the class, this
only references the instance.
If it was different, it would be impossible to e.g. assign a value to a property of an object from inside a method, as using this
would always result in a copied object, which in turn means you would never set the value of the original instance's field, which would be rather bad.
So, to cut a long story short: this
holds a reference, not the value.
HTH 😊