views:

165

answers:

4

I have the following Java code:

public class A {
    private int var_a = 666;

    public A() {
        B b = new B();
        b.method123();
        System.out.println(b.var_b);
    }

    public class B {
        private int var_b = 999;

        public void method123() {
            System.out.println(A.this.var_a);           
        }
    }
}

Which yields 666 and 999. Now, I've tried to set up similar code in c#, but it seems that it is not possible to accomplish the same. If that's the case, how you usually achieve a similar effect when programming in c#?

+12  A: 

You need to make the inner class take an instance of the outer class as a constructor parameter. (This is how the Java compiler implements inner classes)

SLaks
+8  A: 

Inner classes are handled slightly differently between C# and Java. Java implicitly passes a reference to an instance of the outer class to the inner class, allowing the inner class to access fields of the outer class. To gain similar functionality in C#, you just have to do explicitly what Java does implicitly.

Check out this article for some more information.

Corey Sunwold
yes a major, but misunderstood difference
pm100
+1  A: 

Hi,

here is your code:

var_b need to be internal, which is between private and public and means like "accessible for namespace-classes":

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    public class A
    {
        private int var_a = 666;

        public A() 
        {
            B b = new B(this);
            b.method123();
            Console.WriteLine(b.var_b);
        }

        public class B
        {
            private A a = null;

            public B(A a)
            {
                this.a = a;
            }

            internal int var_b = 999;

            public void method123() 
            {
                Console.WriteLine(a.var_a);
            } 
        }
    }


    class Program
    {

        static void Main(string[] args)
        {
            new A();
        }
    }
}
henchman
`var_a` does not need to be `internal`.
SLaks
right! (edited)
henchman
+3  A: 

From a Java perspective, C# inner classes are like java nested classes (what you get if you declare public static class B in your code).

The reason for the difference is that C# supports delegates, which replaces the major use case for Java inner classes. Once delegates are in the language the designers of C# felt it unnecessary to add a distinction between inner and nested classes.

Yishai
The lack of Java-style inner classes actually causes significant pain when you decompose a class using strategy or state patterns.
Jeffrey Hantin