0

So I'm pretty new to C# and I get that reference types are types which store a reference to an object somewhere else in memory (usually on heap). My question is if I have a class which holds other classes as its member variables, do those class member variables also store references ? I ask because a lot of the time you just want your class member variables to be tied to the lifetime of their owning object and it doesn't make sense to have these member variables store references to objects somewhere else in memory. This just adds unnecessary indirection when looking up values for these variables. Now I know one way around this is to make those member variables structs but what if those member variables need inheritance or other class only features? Any insight is appreciated.

Jason
  • 2,198
  • 3
  • 23
  • 59
  • `Now I know one way around this is to make those member variables structs` <= nope, see http://stackoverflow.com/a/1932787/1260204 and https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/ – Igor Mar 20 '17 at 16:54
  • 1
    @Igor No, Jason is correct. The question was not whether or not the inner object lives on the stack but whether the outer object stores a reference or the inner object itself. – Nico Schertler Mar 20 '17 at 16:59
  • @NicoSchertler - ah, I misread. – Igor Mar 20 '17 at 17:39

2 Answers2

5

a lot of the time you just want your class member variables to be tied to the lifetime of their owning object

Well, the member variables are tied to the lifetime of the owning object. As soon as your owning object instance is garbage collected -- as long as there are no other references to its member objects -- they will also be eligible for garbage collection.

As you become more familiar with the language and these concepts, I think you'll find that working with reference types is very much preferable in almost all situations. There is a limited set of situations where you would want to define a value type, like a struct, instead of a class, and the decision to choose struct over class is not tied to the lifetime of the class instances. See MSDN for guidance on choosing between a class and a struct.

rory.ap
  • 34,009
  • 10
  • 83
  • 174
0

My question is if I have a class which holds other classes as its member variables, do those class member variables also store references?

Yes

...you just want your class member variables to be tied to the lifetime of their owning object...one way around this is to make those member variables structs but what if those member variables need inheritance or other class only features?

All objects are flagged for garbage collection when there are no more references to them, so you would just use classes instead of structs. Structs are a rare breed compared to classes.

Rufus L
  • 36,127
  • 5
  • 30
  • 43