When do we use a nested class in C# [duplicate] - c#

This question already has answers here:
Why/when should you use nested classes in .net? Or shouldn't you?
(14 answers)
Closed 9 years ago.
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 inside Vercas.ExplorerView.

Related

Managing similar object classes

In C# i am making a desktop application which has a list of objects from a class called Task.
Each Task contains some Functions which will be executed by the Task when the Task is executed.
My question is how to manage the Functions since there are many types of Functions, there could be a Function with a class to move (In which case it would need vector data) there might also be a class to wait (in which case it would need some integer data).
What is the best way to go about doing this?
My idea is to have each type of function have its own class (wait class & move class) and all those classes inherit from a Function class which has the function Execute().
But even this doesn't work since I'll need to have the user change the data within each of those objects and since none will have the same type of data it gets very difficult.
This is a question about architecture because i am new to programming and i know i will make a bad call about how to go about it and will make my my program impossible to maintain, the only issue with my current design is changing the child classes of function data, for instance knowing to ask for vector data instead of integer data.
FYI There will be many of Function sub classes i only gave two examples, and each will have very unique data. (Links to resources are accepted)
From what I can make from your post your talking about having Classes that extend a parent class. You would define a parent class (or interface) that would have the base methods for what you're doing. If you choose an interface you just make method stubs. The child class if extending a parent class can choose to override the method. If it is a class implementing an interface the class will be forced to make the methods defined in the interface.
Extend from a base class/interface which has all the methods and use a property grid to populate each sub-class with it's unique class specific data.

C#, is it okay to use nested classes for logical structure?

I am having a bit of a debate about the use of nested classes. The situation is that a class name makes sense to be repeated in two or more places, and while there is moderate similarity between each of the different instances, they are generally different. The nested classes are not often (if at all) needed beyond the scope of their parent class.
So then, rather than just coming up with three different class names, this seems to make more sense to me.
class A {
class B {
}
class M {
class B {
}
}
class Q {
class B {
}
}
The obvious problem with that is not functionality, but rather consistency/repetition. I was wondering if other developers have ever struggled with the same thing, and what some of the opinions were.
The .net Design Guide advises against it:
"Do not use public nested types as a logical grouping construct; use namespaces for this."
"Avoid publicly exposed nested types. The only exception to this is when variables of the nested type need to be declared in rare scenarios such as subclassing or other advanced customization scenarios."
That's also what the base class library does: In the System.Web.UI namespace, you have DataGridItem, DataListItem, ListViewItem, MenuItem, RepeaterItem, etc. All of these could be called Item and nested inside DataGrid, DataList, etc. However, this would violate the two principles outlined above.
It looks okay when your classes are small. Once they get bloated, you really start thinking about moving them in separate files.
More to your point, if you want to use both A.B and M.B in the same code you have to always type A.B and M.B, which can be a pain.
If class B has any similarities between each inner class instance, would it make sense for you to abstract the similarities of B to a base class that exists alongside A, M, and Q? (I think so.) Then your inner classes, while they may have the same name, would be a little cleaner.
With that said, this type of structure can be seen for things like Metadata in an MVC application. In that instance you'd have something like:
[MetadataType(typeof(A.Metadata))]
class A
{
protected class Metadata
{
...
}
}
[MetadataType(typeof(B.Metadata))]
class B
{
protected class Metadata
{
...
}
}
In these case the inner classes each serve the same purpose but their implementations vary with each parent class. Also, with the Metadata definitions here, it makes a lot of sense to keep a class that helps describe its parent as an inner class. If there's any chance you might want to re-use the inner classes elsewhere then I would move them outside of their parents.
I think it's a little atypical to see this in practice otherwise. I'm sure there are good examples, but I bet there are more bad examples of this type of pattern.
I would say it is sometimes ok, but usually not a good design, to use private nested classes. I once refactored an existing very large class in my project to give it private nested classes. The reason why I did this was that some methods took dozens of parameters and this gave them a more logical grouping. In this sense I see nested classes as a good quick fix. It made sense because no one outside that class had any use for any of those fields.
Generally, I would shy away from using nested classes in an initial design - and think twice before considering them in a redesign. In maintenance, if you have the time, it is better to redesign the whole class and split them out into separate classes in separate files that are internal.
I think this strategy is also better for testability than using nested classes is. Due to greater dependencies with the outer class and other classes in the application, my refactored nested classes weren't much easier to unit test than the original large class that passed around many parameters. If you split nested classes so that they are on their own, you can write more discrete unit tests that actually test units rather than, effectively, combining the unit tests for the outer class and the inner class. This will give you more confidence in saying, "Yes, the inner class works at the unit test level" and "Yes, the outer class works at the unit test level" (which also tests how it fits together with the inner class, e.g. in computing formulas).
I understand your sample is sort of contrived. Still, if your class names are similar enough - or identical - you really shouldn't make them nested classes. As a general rule you should shy away from using nested classes at all.
If I'm remembering correctly, the .NET Framework Guidelines recommends against using nested classes as well. Nested Type Usage Guidelines is a little old (back to version 1.1), but the principles still apply.
Do not use nested types if the following are true:
The type must be instantiated by client code. If a type has a
public constructor, it probably should not be nested. The rationale
behind this guideline is that if a nested type can be instantiated, it
indicates that the type has a place in the library on its own. You can
create it, use it, and destroy it without using the outer type.
Therefore, it should not be nested. An inner type should not be widely
reused outside of the outer type without a relationship to the outer
type.
References to the type are commonly declared in client code.
Well you can use namespaces to do things like this too (just create a new folder in VS). Which is better for organising and will pretty much give you the same result.
But if the subclass is only relevant to the parent class then I don't see the harm in it.
Then again, if you are calling them the same thing I would guess they do a similar drop and you may want to look into abstraction, perhaps your parent classes could be done differently too. Really depends on what you need them to do though
I like doing that, for me it makes the use more clearer and especially finding names less of a problem. But usally i try to limit this on private classes or public enums.
For example
class Text {
enum Alignment
class UIElement {
enum Alignment
or
class Quadtree {
private class Node
class Octree {
private class Node
Don't create a nested class if there is any chance (or business reason) that you'll have to use it in some other place (use namespace instead and dot not hesitate to create class with long name if you need to).
For instance I use nested class for DTO between my controller and my view, or in a class to represent a cache entry.
If you want to name them the same but have different types you could use different namespaces.
Namespace1.MyClass{}
Namespace2.MyClass{}
This will end up with two different types despite the classes being named the same.
It really depends on the functionality of the nested class. That is very similar to the way the C++ STL defined iterator differently in each class. There's nothing wrong with the practice, per se, as long as the concept of each is truly different based on the encompassing class.
It can be, somewhat, a matter of style and taste, but personally I don't see an issue as long as they are truly different and dependent on the definition of the encapsulating class. It does tend to get more confusing, though, if they are publicly visible outside the class. Thus, I would not personally expose the classes publicly.
There's nothing inherently wrong about nested classes, as long as you stick to the following rules of thumb:
Never public or internal. There are special cases, such as when you're using a nested class to implement IEnumerator. But even then, the class itself should be kept private, since instances of it are being returned as IEnumerator, and it's really just being done as a way to avoid junking up the namespace with classes that aren't supposed to be instantiated.
Keep them small. A private nested class that's really just used for storing and passing around data in a more organized way is fine, and can sometimes be a very useful tool. (Not entirely unlike how anonymous classes are useful.) But if you're looking to use them to package up large chunks of functionality, it becomes a code smell that suggests you might want to consider refactoring the outer class instead.

C# Nested Classes, Clean up Declaration

Is there a way in C# to tidy up the following class declaration?
namespace Application.Namespace
{
public class MasterClass
{
public class FlyingSaucer
{
public class Rotator
{
public class Cube
{
Still maintaining the class structure, just cleaning up the declaration.
No - it's already pretty tidy, given that you've got 4 levels of nesting.
But you almost certainly shouldn't have 4 levels of nesting to start with. Why would you want to do that? You've got a class named subClass1 which isn't a subclass by the normal meaning (i.e. derived from another specific class; subClass1 is only derived from object.)
Nesting classes is fairly rare - I don't think I've ever seen even three levels of nesting, let alone four. Why do you think this is a good idea?
Are there any relationship between
FlyingSaucer -- >Rotator -- >Cube , i am thinking about it is a typical example of Containment.
FlyingSaucer Contains Rotator and Rotator Contains Cube.
so if that is the case , you may consider using Composition by creating properties of Rotator and Cube in FlyingSaucer.
You can inject these dependencies while creating an object FlyingSaucer. This will remove the very deep nesting in your classes and i think , you probably need to access objects of FlyingSaucer , Rotator , Cube from your master class.
so use Composition here it will really make your class hierarchy simpler and easy to extend and maintain.
it looks like you are confusing inheritance with sub classes.
sub classing is usually fairly rare.

Is it possible to have a private class?

I always wonder if it is possible to have a private class? And, what would be the point of having such class?
Thanks for helping.
Yes it is possible to have a private class, but only as an inner class of another class:
public class Outer
{
private class Inner
{}
}
This is usually useful when you want to encapsulate some logic inside of a class (the outer one), but need a more structured/OO design of code to implement it. I have used this pattern in the past when I need a container class to process some information within a method of a class, but the container class has no meaning outside of this logic. Making the container class a private inner class means that its use is localised to the outer class that utilises it.
It is worth noting that with this structure, the inner class has access to the private members of the outer class, but not the other way around.
Having private non-nested classes (Visible only to their namespace and child namespaces only) would allow to clean code boundaries while programming in the same assembly.
Having for example only an interface and a factory visible from other namespaces in the same assembly while still having all the implementation of the interface and utility classes (that no-one have business knowing out of the namespace) there.
It is still possible to do it somewhat with a big partial class replacing a namespace and nested classes inside but it's a very bad hack and unit testing become nearly impossible.
Yes you can - usually they are nested classes inside another type. This means you can aggregate logic into a nested class without exposing the class to anything else. Internal is also useful for nested classes.
Note however that there are some arguments against a design requiring nested classes - I tend to use them when they seem a good fit though.
You can have a private class, inside another class.
You may use a private class to encapsulate logic and implementation. For example you can declare an implementation of an iterator in your implementation of ICollection.

adhoc struct/class in C#?

Currently i am using reflection with sql. I find if i want to make a specialize query it is easiest to get the results by creating a new class inheriting from another and adding the 2 members/columns for my specialized query. Then due to reflections in the lib in my c# code i can write foreach(var v in list) { v.AnyMember and v.MyExtraMember)
Now instead of having the class scattered around or modifying my main DB.cs file can i define a class inside a function? I know i can create an anonymous object by writing new {name=val, name2=...}; but i need a to pass this class in a generic function func(query, args);
Have a look at the DynamicObject maybe it could serve your needs if you hide a Dictionary
behind your implementation of TryGetMember/TrySetMember.
There is a small example on this, follow the link.
Classes (types in general) can not be defined inside methods. Doh.
It's possible (although not simple), but then the resulting class would not be known at compile time, so you wouldn't be able to use v.MyExtraMember. You would basically get a dynamically created anonymous object, so you would have to use reflection to access the extra members.

Categories