I have seen other developers using static classes as namespaces
public static class CategoryA
{
public class Item1
{
public void DoSomething() { }
}
public class Item2
{
public void DoSomething() { }
}
}
public static class CategoryB
{
public class Item3
{
public void DoSomething() { }
}
public class Item4
{
public void DoSomething() { }
}
}
To instantiate the inner classes, it will look like the following
CategoryA.Item1 item = new CategoryA.Item1();
The rationale is that namespaces can be hidden by using the "using" keyword. But by using the static classes, the outer-layer class names have to be specified, which effectively preserves the namespaces.
Microsoft advises against that in the guidelines. I personally think it impacts the readability. What are your thoughts?
Best Answer
Using static classes as namespaces defies the purpose of having namespaces.
The key difference is here:
If you define
CategoryA
,CategoryB<
as namespaces, and when application uses two namespaces :Here if the
CategoryA
orCategoryB
is a static class rather than namespace, the usage for the application is almost same as described above.However, if you define it as a namespace and application uses only 1 namespace (doesn't include
CategoryB
), in that case application can actually use followingBut had you define
CategoryA
as a static class the above is undefined! One is forced to writeCategoryA.something
every time.Namespaces should be used to avoid naming conflicts whereas class hierarchy should be used when class grouping has some relevance to the system model.