Snake Snake - 5 months ago 34
Java Question

nested class can't call parent class in C# but it can in java

if I have parent class that has a nested class. Then in Java the nested class can call a method in its parent class. but in C# you cant do that and it complains saying "cant call outer class method that is not static".

Any reason for why the behaviour is difference?

PS: I am a java programmer and learning C# so excuse my limited knowledge

Example:

public class parent{

void methodA(){ }


public class nested{
void methodB(){
methodA(); /// <-- not allowed in C# but good in java
}
}
}

Answer

It's because if java we have inner classes, while in c# we have nested classes.

An inner class has an implicit reference to the outer class, making it possible to call methods from that class from the inner class.

A nested class is only enclosing the class, there is no reference to the "outer" class. For example, what if we had two instances of the "outer" class, which method would you call?

To get roughly the same thing in C#, you would do something like this

class Outer
{
    private void foo() {}
    class Nested
    {
        private readonly Outer _outer;
        public Nested(Outer outer)
        {
            _outer = outer;
        }

        public void bar()
        {
            _outer.foo(); // now we can call methods from "outer" class
        }
    }
}

This is basically what happens under the hood in java with the inner class syntax as well.

To get a nested class in java, like we have in c#, use static keyword like so

class Outer
{

    static class Inner
    {
    }
}