When we use a nested class in C #

I would like to know when to use nested classes in C # correctly? Do we have incidents in which the use of this is unreasonable and therefore incorrect?

If you can give examples for both situations Thanks

+4
source share
6 answers

It’s convenient for me to use a nested class when you need to encapsulate a data format that will mainly be used in the parent class. This usually happens because the target or data format is so imposed on the parent class that it is not suitable for wider use in your solution.

+8
source

Here is a simple basic introduction to nested classes.

Nested_Classes

+2
source

C # has no way to write a using directive for the target class, so you can access the static members of the class without writing the class name as a classifier (compare with Java import static , which allows this).

So, for users of your classes, this is a little more convenient if you make any public classes as direct members of the namespace, rather than nested in other public classes. Thus, they can output them to the global namespace using the using directive.

For private classes, move on to nuts, preferably place them close to where they are used to increase the readability of your code.

+1
source

I am not sure if there is a place in my world for nested classes. It just blurs the design for me. If you need to hide information inside a class, why not just store it in member variables?

In addition, testing becomes more cumbersome, without the ability to enter a stub instead of a class.

0
source

The user of the nested class is script-specific, as shown below.

1) Organization of code in real situations when there is a special relationship between two objects. 2) Hiding a class inside another class so that you do not want the inner class to be used from outside the class in which it is created.

Suppose you have 2 classes called A and B, and class B depends on class A without class A, you cannot use class B @, this script you can use nested classes

According to my knowledge

The DataRow class is a nested class for a DataTable i.e. you cannot create a DataRow class before u declares an object of the DataTable class

0
source

I find two main resonances:

  • Personalize the class name without destroying it.
    Example: Vercas.ExplorerView , where I personalize the name of my class without destroying the value.

  • Private classes.
    Example: Vercas.ExplorerView.Item used only inside Vercas.ExplorerView .

0
source

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


All Articles