开发者

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 declarin开发者_C百科g 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜