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?