Can structs contain fields of reference types

Can structs contain fields of reference types? And if they can is this a bad practice?


Yes, they can. Is it a good idea? Well, that depends on the situation. Personally I rarely create my own structs in the first place... I would treat any new user-defined struct with a certain degree of scepticism. I'm not suggesting that it's always the wrong option, just that it needs more of a clear argument than a class.

It would be a bad idea for a struct to have a reference to a mutable object though... otherwise you can have two values which look independent but aren't:

MyValueType foo = ...;
MyValueType bar = foo; // Value type, hence copy...

foo.List.Add("x");
// Eek, bar's list has now changed too!

Mutable structs are evil. Immutable structs with references to mutable types are sneakily evil in different ways.


Sure thing and it's not bad practice to do so.

struct Example {
  public readonly string Field1;
}

The readonly is not necessary but it is good practice to make struct's immutable.


Yes, it is possible, and yes, it is usually a bad practice.

If you look at the .NET framework itself, you'll see virtually all structs contain primitive value types alone.


The reason you cannot have mutable structs is because of the behavoir of reference types. Read this article: http://www.yoda.arachsys.com/csharp/parameters.html

When you have a struct that contains an Object (anything that isn't a primitive like int or double) and you copy an instance of the struct, the Object inside isn't "deep" copied, because it is simply a reference (pointer) to a memory location containing the actual class. So if you copy a mutable struct that contains class instances, the copy will be referencing the same instances as the original (Hence bar's list being changed above).

If you absolutely have to have the struct be mutable, make any class instances inside readonly, or - this is the bad practice - try to ensure that you never make a copy of the struct.


Yes they can.

It depends.

Many hold the stance that a struct should be immutable, and in this case, holding a reference to an object could mean it isn't.

But it depends on the situation.