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?
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 tothis
in a function member of a class.
Of structs:
Within an instance constructor of a struct,
this
corresponds to anout
parameter of the struct type, and within an instance function member of a struct,this
corresponds to aref
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 tothis
or by passingthis
as aref
orout
parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With