How the struct data-type can still be a value type when it has a property that is Reference Type?
Is it in real a reference type which is somehow processed with a value type behavior?
How the struct data-type can still be a value type when it has a property that is Reference Type?
Is it in real a reference type which is somehow processed with a value type behavior?
It's simple, really. The field in the struct simply contains a reference to the object that is a reference type. If you're familiar with other languages like C or C++, you might recognize this immediately as being similar to a "pointer", which is essentially a value containing the memory address at which the object being "pointed to" resides.
It doesn't consume any more memory because the struct is only storing a reference to the object, not a complete copy of the object. And when there are no longer any references to that object, it will become eligible for garbage collection.
You might think of this as being similar to how a reference object can be passed "by value". In VB.NET, this is explicitly indicated with the use of the ByVal
keyword. In C#, passing objects by value is simply the default, and you have to indicate explicitly that you want them passed by reference using ref
. Either way, the point is that a reference object can still be passed "by value" because all that's being passed is a copy of the reference, not a copy of the entire object.
Of course, one of the joys of managed environments like .NET is that you don't have to worry about any of these implementation details. Your code will work just fine if you have a struct containing fields that represent both value types and reference types.
Also see my answer to this very similar question: Does it make sense to define a struct with a reference type member? It's worth considering whether or not you really need to define a struct in the first place. Most of the time, a class is a better choice. But whichever one you choose, the behavior in terms of fields containing reference types will be the same.