C# – Is nesting types considered bad practice

cdesignreadability

As noted by the title, is nesting types (e.g. enumerated types or structures in a class) considered bad practice or not? When you run Code Analysis in Visual Studio it returns the following message which implies it is:

Warning 34 CA1034 : Microsoft.Design :
Do not nest type
'ClassName.StructueName'.
Alternatively, change its
accessibility so that it is not
externally visible.

However, when I follow the recommendation of the Code Analysis I find that there tend to be a lot of structures and enumerated types floating around in the application that might only apply to a single class or would only be used with that class. As such, would it be appropriate to nest the type sin that case, or is there a better way of doing it?

Best Answer

Nested types are not bad. The warning you are receiving is not suggesting you never have a nested type. It is simply indicating that your nested type should use an appropriate access modifier and code location.

If the nested type is truly only used inside the containing class (i.e. it is an internal data container or status indicator), then set its access modifier to private.

If the nested type is part of one or more method signatures, then it is not in fact local to the containing class. It represents a message being passed to or from instances of the containing class. In this case, it is arguably better to move the nested type out of the containing class, and give it a more open access modifier such as internal or public.

In short, the warning appears to be recommending that you make local types private, and shared types should stand alone.