Nested type problem
Asked Answered
C

4

7

I just tried to create this simple implementation:

class Test
{
   private int abc = 0;

   public class TestClass
   {
      private void changeABC()
      {
         abc = 123;
      }
   }
}

If I compile it, it will complain:

Cannot access a non-static member of outer type 'A.Test' via nested type 'B.Test.TestClass'

I dont like the solution of setting: static int abc = 0;

Is there any other solution for this?

Chopine answered 22/3, 2011 at 15:16 Comment(1)
@CyberDrew: That's stated in the error: A = Test, B = Test.TestClass"Depone
E
15

You are probably coming from a Java background where this code would work as expected.

In C#, nested types are static (in the parlance of Java), i.e. they are not bound to an instance of the parent class. This is why your code fails. You need to somehow pass an instance of the parent class to the child class and access its member abc.

Epigeous answered 22/3, 2011 at 15:19 Comment(0)
G
9

The inner class needs a reference to an instance of the outer class:

class Test
{
   private int abc = 0;

   public class TestClass
   {
      private void changeABC(Test test)
      {
         test.abc = 123;
      }
   }
}
Goaltender answered 22/3, 2011 at 15:18 Comment(1)
Jeez you guys are fast! I took a whole 4 bloody mins! Maybe I should learn to touch type! =(Browder
B
1

I don't see why TestClass should change the parent Test when its an instance class.

Maybe me example would shed light on this:

class Test
{
   public Test()
   {
     TestClass test = new TestClass();//create a new **instance** here
     test.changeABC(this);//give the instance of Test to TestClass
     Console.WriteLine(abc);//will print 123 
   }
   int abc = 0;

   public class TestClass
   {
      public void changeABC(Test t)
      {
         t.abc = 123;
      }
   }
}

Use Like this:

Test theTest = new Test();
Browder answered 22/3, 2011 at 15:23 Comment(0)
L
1

From C# nested classes are like C++ nested classes, not Java inner classes

When you declare a class inside another class, the inner class still acts like a regular class. The nesting controls access and visibility, but not behavior. In other words, all the rules you learned about regular classes also apply to nested classes.

In Java, the inner class has a secret this$0 member which remembers the instance of the outer class to which it was bound.

In other words, Java inner classes are syntactic sugar that is not available to C#. In C#, you have to do it manually.

Linguistic answered 22/3, 2011 at 15:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.