Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# hack: assignment to "this" [duplicate]

All C# beginners know that class is a reference type and struct is a value one. Structures are recommended for using as simple storage. They also can implement interfaces, but cannot derive from classes and cannot play a role of base classes because of rather "value" nature.

Assume we shed some light on main differences, but there is one haunting me. Have a look at the following code:

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

That is clear as hell - of course we aren't permitted to change object's own pointer, despite of doing it in C++ is a simple practice. But:

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

Why does it work? It does look like struct this is not a pointer. If it is true, how does the assignment above work? Is there a mechanism of automatic cloning? What happens if there are class inside a struct?

What are the main differences of class and struct this and why it behaves in such way?

like image 441
Ilya Tereschuk Avatar asked Jan 02 '14 21:01

Ilya Tereschuk


1 Answers

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

Of classes:

Within an instance constructor or instance function member of a class, this is classified as a value. Thus, while this can be used to refer to the instance for which the function member was invoked, it is not possible to assign to this in a function member of a class.

Of structs:

Within an instance constructor of a struct, this corresponds to an out parameter of the struct type, and within an instance function member of a struct, this corresponds to a ref parameter of the struct type. In both cases, this is classified as a variable, and it is possible to modify the entire struct for which the function member was invoked by assigning to this or by passing this as a ref or out parameter.

like image 113
Ant P Avatar answered Sep 25 '22 19:09

Ant P