简体   繁体   中英

Are nested structs in C# good or bad

I have gotten into the habit of declaring structs nested inside the class that I use them in because that is how I learnt to use them when I first learnt about structs.

If a struct is almost like a class in C# then shouldn't I be declaring structs in a separate file and not nested inside another class?

If the struct is purely an implementation detail of that one class, then it makes perfect sense to declare structs inside a class. I declare structs (and classes!) inside other classes for this reason.

Nested structs, as well as nested classes are good when the nested struct/class is only relevant to use with the outer struct/class, like if it is the type of a member property of the struct/class or only used internally.

Just note that to much nested structs is a warning sign and that you should consider making it classes instead. As MSDN(struct) notes.

Unless you need reference type semantics, a class that is smaller than 16 bytes may be more efficiently handled by the system as a struct.

And the other way around, if your struct with nested structs grow way beyond 16 bytes you should consider using classes instead unless you need the pass by value semantics.

It depends.

If they all share a common theme, maybe putting them in an apropriately named file would be a good idea. Otherwise if they're just a detail of a class I'd put them at the end of the class, right before subclasses (if any).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM