Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a value type implement a ref type

Tags:

c#

oop

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

like image 912
Amit Avatar asked May 24 '13 22:05

Amit


People also ask

How do you convert a value type to a reference type?

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.

How are value type and reference type related to each other?

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.

What is value type reference type C#?

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.

What value does a reference data type have?

Null. The default value of a reference type variable is null when they are not initialized. Null means not refering to any object.


1 Answers

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).

like image 199
Marc Gravell Avatar answered Sep 29 '22 07:09

Marc Gravell