Can structs contain fields of reference types? And if they can is this a bad practice?
Field of Nested Structure In a nested structure, a structure at any level can have fields that are structures, and other fields that are not structures.
You can also pass structs by reference (in a similar way like you pass variables of built-in type by reference). We suggest you to read pass by reference tutorial before you proceed. During pass by reference, the memory addresses of struct variables are passed to the function.
Structs are used for lightweight objects such as Rectangle, color, Point, etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C++ Structure is a collection of different data types.
While value types are stored generally in the stack, reference types are stored in the managed heap. A value type derives from System. ValueType and contains the data inside its own memory allocation. In other words, variables or objects or value types have their own copy of the data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With