Namespace and Nesting Class

I am considering these two scenarios:

class StructuralCase { class Structure { ... } class Material { ... } class Forces { ... } } 

and

 namespace StructuralCase { class Structure { ... } class Material { ... } class Forces { ... } } 

The fact is that inside the "StructuralCase" I will not declare any instance variables, for example, it will function as the "parent" for the rest of the classes.

This led me to consider converting a StructuralClass to a namespace. what do you think about it? Is there a strict rule?

+5
source share
3 answers

You have two different things.

First class example script :

You have an inner class with 3 nested private classes

In your second script, namespace example :

You have 3 internal independent classes without nesting.

If classes should only be used in StructuralCase , use the first example; otherwise, if the classes are independent and not related, the namespace is a way forward.

+4
source

I would just use a namespace because you do not have all the class overhead.

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

+2
source

As a rule, you want to use namespace , if only because it includes using statements, otherwise you must access the class with all nested classes (except for the parent class itself, of course). So in case 1, the external link would have to say

 StructuralCase.Structure s = ... 

instead

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

The functionally only real reason for creating a nested class is

  • So that the nested type has access to non-public members of the parent type (and you hate internal for some reason)
  • So that the subclass is not accessible outside the parent class (for example, a specific struct used for the results of a particular query)
  • So that the child class can share some common parameters from the parent class (for example, factory classes for common types.)
+2
source

Source: https://habr.com/ru/post/1209496/


All Articles