If I assign a simple value type (e.g. an int) to an attribute of type ValueType, is the value then boxed?
For example if I do this:
int i = 4;
ValueType test = i;
Will the value be boxed?
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.
Yes, it will. This is because each type occupies a constant amount of memory at runtime (
inttakes 4 bytes, for example). A struct will take as much space is required to lay out all of the fields in memory.Since you can store any value type in
ValueType, and sinceValueTypewould have to be exactly the same size as the type you’re assigning totest, theValueTypetype is actually a reference type.Consider:
This is perfectly valid code.
testmust occupy a fixed size on the stack, andaandbare different sizes. Hopefully this clarifies why exactlyValueTypecannot itself be a value type. (It’s related to the reason why you can’t derive value types.)