C # hack: assigning "this"

All C # newbies know that class is a reference type, and struct is the value of one. Structures are recommended for use as a simple repository. They can also implement interfaces, but they cannot deduce from classes and cannot play the role of base classes because of rather "value".

Suppose we shed some light on the main differences, but there is one that haunts me. Take a look at the following code:

 public class SampleClass { public void AssignThis(SampleClass data) { this = data; //Will not work as "this" is read-only } } 

This is clear, hell, of course, we are not allowed to change our own pointer to an object , despite the fact that this is done in C ++ - this is a simple practice. But:

 public struct SampleStruct { public void AssignThis(SampleStruct data) { this = data; //Works fine } } 

Why does it work? It looks like struct this not a pointer. If so, how does the work above work? Is there a mechanism for automatic cloning? What happens if there is a class in the structure?

What are the main differences between class and struct this, and why does it behave this way?

+6
source share
1 answer

This section of the C # specification here matters ( 11.3.6 ).

From classes:

Inside an instance constructor or member function of an instance of a class, this classified as a value. Thus, although this can be used to refer to the instance for which the function element was called, it is not possible to assign this to the member of the class function.

From the structures:

Inside the constructor of an instance of a structure, this corresponds to an out parameter of type struct, and inside a member of a function of an instance of a structure, this corresponds to a parameter of ref type struct. In both cases, this is classified as a variable, and you can change the entire structure for which a function element was called by assigning this or passing this as a parameter to ref or out .

+9
source

All Articles