This question already has answers here:
Class.Class vs Namespace.Class for top level general use class libraries?
(7 answers)
Closed 8 years ago.
I am considering these two scenarios:
class StructuralCase
{
class Structure
{
...
}
class Material
{
...
}
class Forces
{
...
}
}
and
namespace StructuralCase
{
class Structure
{
...
}
class Material
{
...
}
class Forces
{
...
}
}
The thing is that inside "StructuralCase" I won't be declaring any instance variables, e.g., it will function as a "parent" for the rest of classes.
This lead me to consider converting StructuralClass to a namespace. What do you think about that? Is there any hard rule?
What you have are two different things.
First scenario class example:
You have an internal class with 3 nested private classes
In your second scenario namespace example:
You have 3 internal independent classes with no nesting.
If the classes should only be used within StructuralCase use the first example, otherwise if the classes are independent and have no relationship then the namespace is the way forward.
Generally, you want to use a namespace, if only because it enables using statements - otherwise you have to refer to the class by all nested classes (except inside the parent class itself, of course). Thus in case 1, outside reference would have to say
StructuralCase.Structure s = ...
instead of
using StructuralCase;
// ...
Structure s = ...
Functionally the only real reason to make a nested class is
So that the nested type has access to nonpublic members of the parent type. If this is a concern over API surface, see instead internal
So that the subclass isn't accessible outside the parent class, such as a specific struct used for results of a specific query
So that the child class can share some Generic Parameters from the parent class, such as factory classes which need the same generic parameters
I would just use Namespace, because you don't all the overhead of a class.
A class has more structure, variables, and methods, and offers layers of inheritance, but if you don't need them, don't use Class.
Related
This question already has answers here:
Closed 10 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Possible Duplicate:
Why does C# not provide the C++ style ‘friend’ keyword?
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?
There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!
Example: To be placed in AssemblyInfo.cs
[assembly: InternalsVisibleTo("OtherAssembly")]
The closest equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:
class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
or if you prefer to put the Inner class in another file:
Outer.cs
partial class Outer
{
}
Inner.cs
partial class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.
In C++, make the Factory a friend of Widget class.
In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.
This involves a fair amount of tedium - exposing all the naturally public properties again in the interface.
There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
public class Class1
{
private int CallMe()
{
return 1;
}
}
You can invoke it using this code:
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."
You can simulate a friend access if the class that is given the right to access is inside another package and if the methods you are exposing are marked as internal or internal protected. You have to modify the assembly you want to share and add the following settings to AssemblyInfo.cs :
// Expose the internal members to the types in the My.Tester assembly
[assembly: InternalsVisibleTo("My.Tester, PublicKey=" +
"012700000480000094000000060200000024000052534131000400000100010091ab9" +
"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8" +
"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e" +
"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499" +
"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88")]
The public key is optional, depending on your needs.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm designing a namespace called ScriptLib. Inside ScriptLib, I have a base class Script with a few derived classes, including but not limited to SPoint and SWhiteSpace and a standalone class ScanGrid.
namespace ScriptLib
{
public enum ScriptType { Point, WhiteSpace }
public enum BoundaryPointMode { FourPoints, TwoPoints }
public enum GridSizingMode { EqualInterval, EqualQuantity }
public class Script
{
public ScriptType ScriptType { get; set; }
//other properties and methods etc.
}
public class ScanGrid
{
public BoundaryPointMode BoundaryPointMode { get; set; }
public GridSizingMode GridSizingMode { get; set; }
//other properties and methods etc.
}
public sealed class SPoint : Script
{
public new ScriptType ScriptType => ScriptType.SPoint;
//other properties and methods etc.
}
public sealed class SWhiteSpace : Script
{
public new ScriptType ScriptType => ScriptType.WhiteSpace;
//other properties and methods etc.
}
//more classes derive from Script and all use ScriptType
}
Script and all its derived classes use ScriptType, and ScanGrid use the other two enums.
At the moment I place them inside the namespace but outside the classes. However, I feel I pollute the namespace this way, since the enums are not used by all classes. Please note that I only started to work on this namespace; more classes and enums will come.
However, if I place ScriptType inside the Script class and the other two in ScanGrid, it leads to the naming problem. I'd like to keep the names for properties, so I need to come up with new names for the enums. Do I name them like: ScriptTypeType, BoundaryPointModeType and GridSizingModeType? To me they do not only read badly but also seem too long, especially the ones for ScanGrid. Imaging the following code:
scanGrid.GridSizingMode = _equalInterval.Checked ?
ScanGrid.GridSizingModeType.EqualInterval:
ScanGrid.GridSizingModeType.EqualQuantity
Is it common to put the enums directly under the namespace even though they are not used by all classes in the same namespace?
Is there a good way of naming the enums and referring to them if I place them inside the classes?
First of all, here is a quote from nested types usage guidelines:
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.
So basically it's a bad idea to put enums into class just to remove them from namespace. Also it's bad idea to expose nested enums via public members - you have public properties of nested enum's type. Now back to your question:
However, I feel I pollute the namespace this way, since the enums are
not used by all classes.
When you are declaring some enum (or another type) in some namespace, it does not mean this enum should be used by all classes in that namespace. E.g. there is enum DayOfWeek in System namespace. And it's not used by all classes in System namespace. It's not even used by most of these classes.
However, if I place ScriptType inside the Script class and the other
two in ScanGrid, it leads to the naming problem.
You have this naming problem, because you are using nested types as they are not supposed to be used. But you can simplify your life a little with C# 6 using static directive. :
using static ScriptLib.Script;
This directive imports static members and nested types contained directly in a type declaration. Thus you will be able to use nested types without name qualification:
scanGrid.GridSizingMode = _equalInterval.Checked
? GridSizingModeType.EqualInterval
: GridSizingModeType.EqualQuantity
I am trying to study about nested class in c#. After reading many documents and goggling, I still not yet clear about when to use nested classes. But as far as I understand I did a small sample program. I am pasting my code below. Is this nested class program implemented in correct logic? . What actually a nested class using for ?. and also I have a doubt arise in this program and I specified that doubt in the program. Please help me ...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Bank bankObj = new Bank();
bankObj.CreateAccount();
bankObj.ShowMyAccountNumber();
}
}
class Bank
{
static int accountNumber; // here if I just declare this as int accountNumber without static it showing an error in the CreatePersonalAccount(int accNo) method's first line ie accountNumber = accNo; as "Cannot access a non-static member of outer type." What actually this error mean ?
public class BankAccountSection
{
public bool CreatePersonalAccount(int accNo)
{
accountNumber = accNo;
return true;
}
}
public void CreateAccount()
{
bool result = new BankAccountSection().CreatePersonalAccount(10001);
}
public void ShowMyAccountNumber()
{
MessageBox.Show(accountNumber.ToString());
}
}
Nested classes are usually used for small utility classes that have no use outside the enclosing (outer) class. For that reason, nested classes are usually private. (There's even an FxCop rule for that.)
Your code
In your case, the nested class BankAccountSection is not really useful, since it has no state by itself. CreatePersonalAccount might as well just be a method of the outer class.
Regarding static int accountNumber;: This will make accountNumber a shared field across all Bank objects, which defeats the whole purpose. Don't do that. If you really need to set a field of the Bank object inside the inner class, you need to pass a reference of the Bank object to the inner class. (This is different to Java, where such a reference is available automatically under some circumstances.) In your particular case, just get rid of the inner class.
Examples for legitimate use cases
You have a large algorithm inside a method. You realize that extracting this algorithm into its own class using many small methods and instance variables would increase readability. Since the algorithm is very specific and probably not useful for other classes, you put the algorithm into an inner class. Thus, you avoid cluttering your outer class with instance variables only used by that algorithm.
You create a List data structure, which is internally implemented as a linked list. Since you don't expose the list nodes to the outside world, you make the nodes an inner class.
Related:
Why/when should you use nested classes in .net? Or shouldn't you?
You seem to think that nested classes in C# behave how they do in Java. That in other words, unless a nested class is declared as static, that it will share the instance of the enclosing class. In C# this is not the case. There is no such thing as that sort of thing in C# -- all nested classes are implicitly static.
This is why you cannot access accountNumber from the nested class unless that field is declared static. (Since the nested class has no access to any particular instance) The idomatic solution to this problem in C# is to pass the instance of the enclosing class into the nested class (presumably by passing this via a constructor argument when instantiating it).
First, that's not a nested class, they are just two classes in one file.
Now, even if it were a nested class, this would probably be an example of when NOT to use nested classes. You should definitely separate your logic from your GUI logic.
I'm don't really think you should be using nested classes anyway, they are in my opinion hard to mantain, but I might be wrong. If I really needed to use nested classes I'd probably do so only when the child class is tightly related.
The error is because you can not access a member of a non static class without its object.
if you do so then it must be declared static.
This question already has answers here:
Why/when should you use nested classes in .net? Or shouldn't you?
(14 answers)
Closed 10 years ago.
In this stackoverflow answer a commenter mentioned that "private nested classes" can be quite useful so I was reading about them in articles such as this one which tend to explain how nested classes function technically, but not why you would use them.
I suppose I would use private nested classes for little helper classes that belong to a larger class, but often I will need a helper class from another class and so I would just have to take the extra effort to (1) make the nested class non-nested or (2) make it public and then access it with the outer-class prefix on it, which both seems to be extra work without any added-value for having the nested class in the first place. Hence in general I really don't see a use case for nested classes, other than perhaps to keep classes a bit more organized into groups, but I that also goes against the one-class-per-file clarity that I have come to enjoy.
In what ways do you use nested classes to make your code more manageable, readable, efficient?
You've answered your own question. Use nested classes when you need a helper class that is meaningless outside the class; particularly when the nested class can make use of private implementation details of the outer class.
Your argument that nested classes are useless is also an argument that private methods are useless: a private method might be useful outside of the class, and therefore you'd have to make it internal. An internal method might be useful outside of the assembly, and therefore you'd make it public. Therefore all methods should be public. If you think that's a bad argument, then what is different about you making the same argument for classes instead of methods?
I make nested classes all the time because I am frequently in the position of needed to encapsulate functionality in a helper that makes no sense outside of the class, and can use private implementation details of the outer class. For example, I write compilers. I recently wrote a class SemanticAnalyzer that does semantic analysis of parse trees. One of its nested classes is LocalScopeBuilder. Under what circumstances would I need to build a local scope when I am not analyzing the semantics of a parse tree? Never. That class is entirely an implementation detail of the semantic analyzer. I plan to add more nested classes with names like NullableArithmeticAnalyzer and OverloadResolutionAnalyzer that are also not useful outside of the class, but I want to encapsulate rules of the language in those specific classes.
People also use nested classes to build things like iterators, or comparators - things that make no sense outside of the class and are exposed via a well-known interface.
A pattern I use quite frequently is to have private nested classes that extend their outer class:
abstract public class BankAccount
{
private BankAccount() { }
// Now no one else can extend BankAccount because a derived class
// must be able to call a constructor, but all the constructors are
// private!
private sealed class ChequingAccount : BankAccount { ... }
public static BankAccount MakeChequingAccount() { return new ChequingAccount(); }
private sealed class SavingsAccount : BankAccount { ... }
and so on. Nested classes work very well with the factory pattern. Here BankAccount is a factory for various types of bank account, all of which can use the private implementation details of BankAccount. But no third party can make their own type EvilBankAccount that extends BankAccount.
Returning an interface to the caller whose implementation you want to hide.
public class Outer
{
private class Inner : IEnumerable<Foo>
{
/* Presumably this class contains some functionality which Outer needs
* to access, but which shouldn't be visible to callers
*/
}
public IEnumerable<Foo> GetFoos()
{
return new Inner();
}
}
Private helper classes is a good example.
For instance, state objects for background threads. There is no compelling reason to expose those types. Defining them as private nested types seems a quite clean way to handle the case.
I use them when two bound values (like in a hash table) are not enough internally, but are enough externally. Then i create a nested class with the properties i need to store, and expose only a few of them through methods.
I think this makes sense, because if no one else is going to use it, why create an external class for it? It just doesn't make sense to.
As for one class per file, you can create partial classes with the partial keyword, which is what I usually do.
One compelling example I've run into recently is the Node class of many data structures. A Quadtree, for example, needs to know how it stores the data in its nodes, but no other part of your code should care.
I've found a few cases where they've been quite handy:
Management of complex private state, such as an InterpolationTriangle used by an Interpolator class. The user of the Interpolator doesn't need to know that it's implemented using Delauney triangulation and certainly doesn't need to know about the triangles, so the data structure is a private nested class.
As others have mentioned, you can expose data used by the class with an interface without revealing the full implementation of a class. Nested classes can also access private state of the outer class, which allows you to write tightly coupled code without exposing that tight coupling publicly (or even internally to the rest of the assembly).
I've run into a few cases where a framework expects a class to derive from some base class (such as DependencyObject in WPF), but you want your class to inherit from a different base. It's possible to inter-operate with the framework by using a private nested class that descends from the framework base class. Because the nested class can access private state (you just pass it the parent's 'this' when you create it), you can basically use this to implement a poor man's multiple inheritance via composition.
I think others have covered the use cases for public and private nested classes well.
One point I haven't seen made was an answer your concern about one-class-per-file. You can solve this by making the outer class partial, and move the inner class definition to a separate file.
OuterClass.cs:
namespace MyNameSpace
{
public partial class OuterClass
{
// main class members here
// can use inner class
}
}
OuterClass.Inner.cs:
namespace MyNameSpace
{
public partial class OuterClass
{
private class Inner
{
// inner class members here
}
}
}
You could even make use of Visual Studio's item nesting to make OuterClass.Inner.cs a 'child' of OuterClass.cs, to avoid cluttering your solution explorer.
One very common pattern where this technique is used is in scenarios where a class returns an interface or base class type from one of its properties or methods, but the concrete type is a private nested class. Consider the following example.
public class MyCollection : IEnumerable
{
public IEnumerator GetEnumerator()
{
return new MyEnumerator();
}
private class MyEnumerator
{
}
}
I usually do it when I need a combination of SRP (Single Responsibility Principal) in certain situations.
"Well, if SRP is your goal, why not split them into different classes?" You will do this 80% of the time, but what about situations where the classes you create are useless to the outside world? You don't want classes that only you will use to clutter your assembly's API.
"Well, isn't that what internal is for?" Sure. For about 80% of these cases. But what about internal classes who must access or modify the state of public classes? For example, that class which was broken up into one or more internal classes to satisfy your SRP streak? You would have to mark all the methods and properties for use by these internal classes as internal as well.
"What's wrong with that?" Nothing. For about 80% of these cases. Of course, now you're cluttering the internal interface of your classes with methods/properties that are only of use to those classes which you created earlier. And now you have to worry about other people on your team writing internal code won't mess up your state by using those methods in ways that you hadn't expected.
Internal classes get to modify the state of any instance of the type in which they are defined. So, without adding members to the definition of your type, your internal classes can work on them as needed. Which, in about 14 cases in 100, will be your best bet to keep your types clean, your code reliable/maintainable, and your responsibilities singular.
They are really nice for, as an example, an implementation of the singleton pattern.
I have a couple of places where I am using them to "add" value, as well. I have a multi-select combobox where my internal class stores the state of the checkbox and the data item as well. no need for the world to know about/use this internal class.
Private anonymous nested classes are essential for event handlers in the GUI.
If some class is not part of the API another class exports, it must be made private. Otherwise you are exposing more than you intend. The "million dollar bug" was an example of this. Most programmers are too slack about this.
Peter
The question is tagged C# so I'm not sure this is of interest, but in COM you can use inner classes to implement interfaces when a class C++ implements multiple COM interfaces... essentially you use it for composition rather than multiple-inheritance.
Additionally in MFC and perhaps other technologies you might need your control/dialog to have a drop-target class, which makes little sense other than as a nested class.
If it is necessary for an object to return some abstract information about its state, a private nested class may be suitable. For example, if an Fnord supports "save context" and "restore context" methods, it may be useful to have the "save context" function return an object of type Fnord.SavedContext. Type access rules aren't always the most helpful; for example, it seems difficult to allow Fnord to access properties and methods of a Fnord.SavedContext without making such properties and methods visible to outsiders. On the other hand, one could have Fnord.CreateSaveContext simply create a New Fnord.SaveContext with the Fnord as a parameter (since Fnord.SaveContext can access the internals of Fnord), and Fnord.LoadContextFrom() can call Fnord.SaveContext.RestoreContextTo().
This question already has answers here:
Why/when should you use nested classes in .net? Or shouldn't you?
(14 answers)
Closed 10 years ago.
I am thinking that if a class will be instantiated only in another class so it is right to use it nested in that class.I think this will help us good design.When i look at my project i have almost never seen such nested structure.But if i try to nested classes so this time another questions appear in my mind.For example
I have Board class, Move classes such as ShortCastle,LongCastle,EnPassant,Promote and Pieces like Pawn,Queen,Rook,Knight etc. So it is clear Board classes will instantiate Piece classes and Piece classes will instantiate Move classes. For a good design,Promote move class should to be nested of Pawn because only pawn can promote itself.short and long Castles should to be nested of King because only king can have such type moves.
Trying to put all Piece classes into Board class is not looking good design because 8-9 class will be inside of Board class and it will really annoying one Board class file will be too large and hardly readable.I prefer keep each piece class in another file. Good that we can create partial Board class but still isn't it annoying 8-9 Partial Board class files will hold each piece class? Is it better to not make them nested ? Same about Pieces Create another partial Piece file just for another Move type class ? If nested class just take small space so it wouldn't be any problem but if it takes many methods ?
I think you are too generous with nested classes.
Have a look at this design guideline for nested types.
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.
The pieces may belong to a board(Piece-collection as a member?) but could coexist without of it. You might f.e. want to reuse boards without pieces(themes etc) and also reuse pieces without a board(positions etc).
Private members from parent class are accessible to Nexted Class methods.
Nexted class allows reduce complexity without broad Scope.
For a good design,Promote move class should to be nested of Pawn because only pawn can promote itself.
I don't really agree. Just because you can nest classes doesn't mean you should. Ask yourself what benefit you're getting from nesting these classes.
If you truly, truly think nested classes make sense for your design (see Tim Schmelter's admonitions) but feel the file size is too big, the use of partial classes is fine to split the nested class defintions into their own files. Or if the nested classes are small enough on their own but you have a large number of them, put all the nested classes into one partial file.
Parent.cs:
public partial class Parent
{
void SomeMethod()
{
Nested1 n1 = new Nested1();
Nested2 n2 = new Nested2();
}
}
Nested.cs:
public partial class Parent
{
private class Nested1
{
}
private class Nested2
{
}
}
Nested classes have their place but can be confusing to work with. I found a webpage that shows how to use some .Net classes to get Facebook's JSON-output of wall posts at http://www.virtualsecrets.com/graph-api-json-facebook-handler.html What is interesting here is that classes are nested inside of classes, inside of other classes - so it can be done, just a bit complex. :)