Nested class in C# - c#

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.

Related

If two class inherit an static field, will the objects of those classes share the same value?

Is it possible that different objects of different classes can use one shared item among themselves (e.g for providing some information on the fly) or better a means of communication between different objects of two different classes ?
Class Base
{
public static string SomeThing = "Shared With All";
}
Class Der1 :Base
{
public void DoSomeThing()
{
SomeThing = "SomeThing Goes in here...";
}
}
Class Der2 :Base
{
public void DoSomeThingElse()
{
Console.WriteLine"(SomeThing);
}
}
....
{
Der1 dr1 = new Der1();
dr1.DoSomeThing();
Der2 dr2 = new Der2();
dr2.DoSomeThingElse(); //shows 'SomeThing Goes in here...'
}
If it helps more, I am trying to create a designer of some kind and so I need to get track of all controls and their associations on the designer. Actually there are only two objects at the moment (one called transaction and the other is called place, different places can be associated with different transactions, and this association is done by the user clicking on one place and pointing to the other transactions (have you seen Proteus? something like that).
So this approach will help me know which object is referring which other object and thus and association between the two can be easily spotted and saved.
The static field isn't really inherited in the same way as normal fields are. There's still just one static field, Base.SomeThing. Both of your derived classes are referring to the same field: if anything changes Base.SomeThing, everything that accesses that field will see the change.
Yep, you've invented a global variable :) It is also almost always a sign of bad design. Try solving your task differently.
It is possible, but think carefully about communicating in this way inside the class. There is no good way to account for concurrency issues and very hard to debug if the value is set multiple places.
You can either use static var's or share stuff using setter and getter. These are basic operators in OOP.
A static field belongs to the class that declares it. Any subclasses of that class gets access to that one static field.
There are some caveats here. Declaring a static variable on a Generic class means that one copy of that variable exists for each closed type of that generic. Here's an example to clarify
public class StaticGenericTest<T>
{
private static int count=0;
public StaticGenericTest()
{
count++;
}
}
If you instantiate a StaticGenericTest<int> and a StaticGenericTest<string> they would have different values for count. However a subclass of StaticGenericTest<int> would share count with all other subclasses of StaticGenericTest<int>.
Also you'll get funny behavior using the ThreadStatic attribute (because you'll get one copy of count per thread) and/or static constructors.
As someone mentioned, Static fields are global state and should be protected as such and used with caution.

Accessing a private method from another class

I have two repository classes (RepositoryFactory and BaseRepository) implementing different interfaces within the same project. The BaseRepository class has a private method that would be now needed also in the other class, with the same implementation.
Instead of duplicate the method in order to keep it private, I was thinking to a possible alternative, although so far I could not find a good solution since by definition a private method has scope only in its own class.
Using inheritance and change the method to "protected" would also not be an option, since the two classes are not linked semantically. I cannot use a public property giving back the result of the method since the return type is void.
You can use reflection. Here's an example:
MethodInfo privMethod = objInstance.GetType().GetMethod("PrivateMethodName", BindingFlags.NonPublic | BindingFlags.Instance);
privMethod.Invoke(objInstance, new object[] { methodParameters });
It's not possible to do what you want in C#. The closest you can have is internal, which makes the member visible to an entire assembly. It might also be possible to make the two classes private and nested inside another class, but this isn't always appropriate.
Mads Torgersen, who works on C#, has this to say about it:
I've seen a number of proposals trying to grapple with some notion of "class set accessibility." The complication of course is that, unlike existing accessibilities, there is not already a natural group (everyone, assembly, derived classes, single class) to tie it to, so even with another accessibility modifier you still also need syntax (or something) to define the group.
There are several ways to slice it. I haven't seen a proposal that is obviously right, but I think the problem is relevant, and I will take this up with the design team.
(source)
You can, but it looks awkward. This takes advantage of nested classes being able to access private stuff from the containing class. However, even if something is possible doesn't mean you should do it. If you just change the modifier to internal you get the same behavior and since the two classes are coupled together then it makes sense to ship them in the same assembly, so internal modifier is the correct answer.
public class BaseRepository
{
public sealed class RepositoryFactory
{
public static BaseRepository Create()
{
var repo = new BaseRepository();
repo.MethodRequiredByRepositoryFactory();
return repo;
}
}
private void MethodRequiredByRepositoryFactory() { }
}
Reference
Possible by using reflection
Create a console application in Visual Studio.
Add 2 namespaces
2.1. System
2.2. System.Reflection
Now create a class and inside that class create one method that will be private as follows:

What are reasons why one would want to use nested classes? [duplicate]

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().

Where and how to use nested classes? [duplicate]

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. :)

Global access vs. local variables

I have two objects that I will be mainly use inside of single class. I will initialize them at the beginning and use them throughout the life of the program. Now, my question is that if I should just create them as global variables and access them anywhere in the code (in side of single class) or I should create them as local variables and pass them as parameters to other functions. I just want to see what would be the best programming practice.
I am using C#.
Thanks.
In general you should avoid global variables. If it will be practical, I recommend keeping them as locals and passing them as parameters to your functions.
As Josh pointed out, if these variables are only used inside a single instance of the class, then you should just make them private (or protected) members of that class and be done with it. Of course, then they could only be passed in as parameters to other methods with the same access level (IE, private).
Alternatively, you may consider using the Singleton Design Pattern, which is slightly cleaner (and preferable) to using globals.
If the scope of the objects is the lifetime of the class they are instantiated in, then they should be private member variables.
If they do not maintain state themselves, then you should make them static classes.
You should still pass them around as variables, or at least create property accessors to get at the backing field. This way you can change implementation details without blowing up your code.
SOLID design principles are a good place to start when thinking about these things.
I have two objects that I will be
mainly use inside of single class. I
will initialize them at the beginning
and use them throughout the life of
the program.
This sounds like a perfect time to use a private static readonly variable. These can be initialized in their declaration, or you can make a static constructor to initialize them.
The fact that you are only referencing these objects within a single class is key point. There are other better ways to do things if these objects are ever needed outside of the single class.
If the objects will be the same for every instance of the class then
static const double PI = 3.14158;
You should generally use accessor methods (e.g. getters and setters) and keep your internal variables private. This way the rest of your code, outside of your class, is not dependent on your actual variables.
See this tutorial.
If your class is dependent on these 2 objects then they should probably be members on the class itself. Something like this (where A is the class you are talking about and B is one of the objects you initialize:
public class A
{
private B _b;
public A(B b)
{
_b = b;
}
public void DoSomething()
{
//do something with _b;
}
private void DoSomethingElse()
{
//do something else with _b;
}
}
In this example A is dependent on B (so you pass your instance of B into A's constructor or through some Dependency Injection framework). It wouldn't make a lot of sense for every method on class A to need a parameter of type B to be passed to it.
I think in this case you should ask what makes more sense. Is there some kind of relationship between the 2 objects and the new class. Also, how often are they used in the class.
Generally, If only a couple of methods use the objects, pass them around otherwise, instantiate them as class level variables (possibly using private static readonly as Jefferey suggests) and use them in the class. Making the code more readable should be your goal here.

Categories

Resources