Why are interfaces reference types? As far as I understand, an interface is a contract between classes (or structs), so why is it a type at all? I would have thought it is neither a value type or a reference type.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To be treated as a struct the compiler must know at compile time what the concrete type is, to reserve the right space on the stack. This means that even if a struct implements
IFoo, then with:then the assignment to
foois a boxing operation. You could say “the compiler should spot that it is only ever a foo and use the ‘constained’ opcode”, but in the general case (with multiple assignments tofooetc) this isn’t possible (I would hazard a guess that it will hit the “halting problem”).There is also an issue of virtual vs static call, but the “constrained” opcode works around that.
Basically, any usage of the interface must always be treated as a reference.
There is one exception to this: generic constraints.
If you have
here the method is JITted once per value-type, so the stack-space needed for
Tis known; the call toBaris “constrained” and can be virtual or static automatically as needed.