I came across a scenerio where a value type is implementing ref. type.
Just want to know how come is that possible ( what goes behind the scene ?)
A struct is a value type and interface a ref. type but a struct can implement interface without any error...
Any thoughts? Thanks in advance
The process of converting a Value Type variable (char, int etc.) to a Reference Type variable (object) is called Boxing. Boxing is an implicit conversion process in which object type (super type) is used. Value Type variables are always stored in Stack memory, while Reference Type variables are stored in Heap memory.
Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable.
Value types and reference types are the two main categories of C# types. A variable of a value type contains an instance of the type. This differs from a variable of a reference type, which contains a reference to an instance of the type.
Null. The default value of a reference type variable is null when they are not initialized. Null means not refering to any object.
Actually, it does it in two different ways at once.
Firstly, any value-type can be boxed into a reference-typed object instance. This box is invented by the runtime on demand and will implement the interface in the way you expect - i.e. the box will implement any interfaces the value-type implements.
However, the CLI also allows for a "constrained call". A constrained call turns a virtual call into a static call but only in exactly to the scenario where a value type implements an instance method by way of override or interface implementation (otherwise it is implemented by the JIT as a virtual call). In particular generics makes extensive use of constrained calls (the constrained opcode was added at the same time as generics, for exactly this reason).
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