Can structs contain fields of reference types? And if they can is this a bad practice?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
Mutable structs are evil. Immutable structs with references to mutable types are sneakily evil in different ways.