Would like to know when it is right to uses a nested classes in C#? Do we have incidents in which the use of it is unjustified and therefore not correct?
If you can give examples for both situations Thanks
I find it's convenient to use a nested class when you need to encapsulate a format of data that is primarily going to be used within the parent class. This is usually because the purpose or format of the data is so bespoke to the parent class that it's not really suitable for wider use within your solution.
Here's a simple basic introduction to nested classes.
Nested_Classes
C# doesn't have a way to write a using
directive to target a class, so that the static members of the class can be accessed without writing the class name as a qualifier (compare with Java's import static
, which does allow that).
So for users of your classes, it is a little more convenient if you make any public classes as direct members of a namespace, not nested within other public classes. That way they can pull them into the global namespace with a using
directive.
For private classes, go nuts, preferably put them close to where they are used to enhance the readability of your code.
I am not sure if there is room in my world for nested classes. It simply blurs the design for me. If you need to hide the information inside a class, why not just store it in member variables?
Besides, testing becomes more cumbersome without the ability to inject a stub in the place of the class.
User of Nested class is depending upon the scenario like below.
1) Organizing code into real world situations where there is a special relationship between two objects. 2) Hiding a class within another class so that you do not want the inner class to be used from outside of the class it is created within.
Suppose you have 2 classes called A and B and class B is depending upon class A without class A you cannot use class B @ that scenario you can use nested classes
As per my knowledge
DataRow class is nested class for DataTable i.e you cannot create a DataRow Class untill u declare a object of DataTable class
I find two main resons:
Personalize a class' name without ruining it.
Example:Vercas.ExplorerView
, where I personalize the name of my class without ruining the meaning.Private classes.
Example:Vercas.ExplorerView.Item
is used only insideVercas.ExplorerView
.
精彩评论