I was recently looking into internals of CancellationToken structure and discovered a bit of weird construct (to be more precise, assignment of value to this keyword).
Code of one of its constructors is as following:
public CancellationToken( bool canceled )
{
this = new CancellationToken();
if ( canceled )
{
this.m_source = CancellationTokenSource.InternalGetStaticSource( canceled );
}
}
What is the meaning of line on which the assignment to this keyword occurs?
Please note that assignment to this keyword is not possible for classes – error Cannot assign to '<this>' because it is read-only occurs.
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..
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
thisin classes were possible, and you’d have said something likethis = 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).