3

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());
    }
}
3
  • Your code doesn't show a nested class at all. It has two separate top-level classes. Commented Feb 27, 2013 at 6:42
  • 4
    @Jon, BankAccountSection is nested inside Bank Commented Feb 27, 2013 at 6:43
  • 1
    Imo/ime there is not much use for nested classes Commented Feb 27, 2013 at 6:43

4 Answers 4

7

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:

Sign up to request clarification or add additional context in comments.

2 Comments

I would suggest that if a Thing defines a type whose instances will exist to act on a particular instance, having the type be a Thing.Frobber conveys that relationship much more clearly than does ThingFrobber. This is especially true in many situations involving generics. List<T>.Enumerator is clearer than would be ListEnumerator<T>. Further, in some cases involving things like adapters, a Name1<T1,T2,T3>.Name2<T4> may express the relationships among the types more cleanly than would Name<T1,T2,T3,T4>`.
Note also that if one wants to invoke a generic method in such fashion as to specify some parameters but not others, one may do that by having a static class ClassName<T> contain a method MethodName<U>(U param). I know of no better way to allow specification of some but not all of a method's generic types.
0

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

2 Comments

Are you saying that BankAccountSection is implicitly static - i.e. it can only have static members? The CreatePersonalAccount isn't declared as static in the example given.
No, I'm saying that it's not an "instance class" (which has no analog in C#, but does exist in Java)
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.