Can structs contain fields of reference types

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.

Leave a Comment