c# - Namespace vs nesting class

Class.Class vs Namespace.Class for top level general use class libraries?

7 answers

网友答案:

What you have are two different things.

First scenario class example:

You have an internal class with 3 nested private classes

In your second scenario namespace example:

You have 3 internal independent classes with no nesting.

If the classes should only be used within StructuralCase use the first example, otherwise if the classes are independent and have no relationship then the namespace is the way forward.

网友答案:

I would just use Namespace, because you don't all the overhead of a class.

A class has more structure, variables, and methods, and offers layers of inheritance, but if you don't need them, don't use Class.

网友答案:

Generally, you want to use a namespace, if only because it enables using statements - otherwise you have to refer to the class by all nested classes (except inside the parent class itself, of course). Thus in case 1, outside reference would have to say

StructuralCase.Structure s = ...

instead of

using StructuralCase;
// ...
Structure s = ...

Functionally the only real reason to make a nested class is

So that the nested type has access to nonpublic members of the parent type (and you hate internal for some reason)

So that the subclass isn't accessible outside the parent class (such as a specific struct used for results of a specific query)

So that the child class can share some Generic Parameters from the parent class (such as factory classes for generic types.)