Assignment of a struct value to this keyword
This is a very little known feature of C# - this allows a struct to overwrite its own data.
As far as practical application goes, you're not going to find many uses for this..
struct MyStruct
{
int a = 1;
int b = 2;
int c = 3;
public void Mutate()
{
a = 10;
b = 20;
c = 30;
}
public void Reset()
{
a = 1;
b = 2;
c = 3;
}
public void Reset2()
{
this = new MyStruct();
}
// The two Reset methods are equivilent...
}
Thinking about it more, there's a fundamental difference in what "this" means when you're dealing with value types vs reference types.
When you call "this" on a reference type - what you get is a pointer that lives on the stack, you don't actually get the object itself. The pointer implicitly dereferences back to the object on the heap, which abstracts the indirection. Now if assigning to this
in classes were possible, and you'd have said something like this = new MyReferenceType()
, you'd have changed the pointer to point to a different heap object in the current scope - you wouldn't have changed the original object itself in the heap, nor would it have caused any other references/pointers to refer the new heap object. Its very likely that as soon as your mutated pointer would have gone out of scope - the new heap object you'd have created would have been subject to garbage collection.
When you call "this" on a value type - you are getting the actual object, not a reference or pointer. There is no indirection so you are free to overwrite the raw bits at this memory location (which is exactly what the default constructor does).