Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can structs contain fields of reference types

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

like image 361
James Hay Avatar asked Jun 03 '09 16:06

James Hay


People also ask

Can structs have fields?

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.

Are structs passed references?

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.

Is struct a reference type in C++?

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.

Where reference types are stored?

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.


2 Answers

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.

like image 106
Jon Skeet Avatar answered Oct 21 '22 23:10

Jon Skeet


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.

like image 29
JaredPar Avatar answered Oct 21 '22 22:10

JaredPar