Consider some properties of structs, first:
- In C#, all structs inherit implicitly from the class
System.ValueType
, which in turn inherits from System.Object
.
- In C#, a struct cannot inherit from any other struct. A direct consequence of this is that if you have an expression whose statically known type is a struct type, then the instance of that expression has a runtime type equal to the statically known type. (In simple terms, if you have an
int
expression, then the contained instance is definitely exactly an int
.)
For runtime type checks, the situation is simple:
- If you ask a struct whether it is an
object
, then the CLR looks up the relevant metadata and finds System.Object
in the hierarchy, so it answers true
.
For compile-time type checks, the compiler has to make some decisions :
- If a struct expression is assigned to a value type storage location, then:
- If the types are not the same but there is an implicit conversion defined, the conversion is invoked and then the assignment happens.
- If there is no implicit conversion but the assignment is valid (the target struct type is the same as the source struct type), the assignment happens directly.
- If a struct expression is assigned to a reference type storage location, then:
- If there is an implicit conversion defined, the conversion is invoked and then the assignment happens.
- If there is no implicit conversion but the assignment is valid (the target class is
object
or the target interface is an interface that the struct type implements), then a boxing operation occurs and then the assignment happens.
Notice that by storage location I mean variable, field, array slot, method argument, and so on.
So, it doesn't matter if you're assigning a struct instance to an object
variable or if you're passing a struct instance as an argument to a method that expects an object
expression (at least, assuming no overload resolution involved) - in both cases, the same rules apply.
(The situation is probably a little bit more complicated, but I believe the above covers the general cases.)