2

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?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
pencilCake
  • 51,323
  • 85
  • 226
  • 363

1 Answers1

4

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.

Community
  • 1
  • 1
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • A *field* of a reference type works as you describe. A *property* of a reference type will do whatever it's coded to do. One could, for example, have a structure with a property of type `int[]` whose `get` method created a new array each time it was called. I dislike that pattern (better would be either a method which would take an existing array and populate it, or a `GetNewWhatever()` method whose name would imply that what's returned is a *new* array. – supercat Nov 19 '12 at 18:11