Curiosity: Converting a C# struct into an object still copies it

会有一股神秘感。 提交于 2019-12-08 14:14:24
Zruty

You are observing the process called boxing. It essentially converts a value type into a reference type.

Also, this now allows me to set point to null whereas structs can't be set to null. Is the struct automatically converted into a nullable type?

You are misunderstanding the whole process:

int i = 5;
object o = i; //Creates a new Int32 with value 5 and assigns it to the object'o' reference storing the value on the garbage collected heap. This is what is called boxing.
object o = null //Simply assigns 'null' to the object reference, it does nothing to the boxed value type 'o' was referencing before.

In the example above the boxed int will eventually be collected by the GC from the garbage collected heap as no live reference is pointing at it anymore.

You are not converting myPoint to an object, you are just creating a copy of the myPoint structure (through the GetPoint method) and assigning an object reference to it.

Although Microsoft in some sense claims that all types derive from object, it's more helpful to regard value types as being things which are totally outside the type system, but which have boxed equivalents within the typing system (all of which derive from ValueType), along with widening conversion operators between them and the boxed equivalents. If one passes an a structure to a routine which expects an Object, one isn't really passing a value type, but rather the boxed equivalent of a value type. If that is passed around to other routines that expect Object, they will continue to use the same boxed object. If it is passed to routines that expect the structure, it will be converted back to a structure for use with those routines. Note that each time it's converted, a snapshot is taken of the value; changes to the snapshot will not affect the copied entity, nor vice versa.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!