Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested type problem

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?

like image 888
olidev Avatar asked Mar 22 '11 15:03

olidev


People also ask

What is nested class with example?

A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed.

What are the types of nested classes?

There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes. A class created within class and outside method.

What are the two types of nested classes?

Terminology: Nested classes are divided into two categories: non-static and static. Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class.


1 Answers

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.

like image 195
Konrad Rudolph Avatar answered Oct 29 '22 08:10

Konrad Rudolph