-3

In WPF I face this problem frequently when I bind list to DataGrid and DataContext = new A();

class A
{
  int x;
  List<B> list;

  class B
  {
    B()
    {
      // want to use x here, but i can't
    }
  }
}

Please suggest something

Ivan
  • 57
  • 6
  • 4
    You are defining a class. Not a nested instance. – Myrtle Dec 01 '14 at 13:11
  • There is probably a cleaner way of doing what you want without this. – crashmstr Dec 01 '14 at 13:12
  • possible duplicate of [Cannot access nested classes or members of base class](http://stackoverflow.com/questions/25123351/cannot-access-nested-classes-or-members-of-base-class) – t3chb0t Dec 01 '14 at 13:21
  • possible duplicate of [Cannot access a non-static member of outer type via nested type](http://stackoverflow.com/questions/16320935/cannot-access-a-non-static-member-of-outer-type-via-nested-type) – Peter Duniho Dec 01 '14 at 23:38

1 Answers1

7

The reason you cannot access it is that you cannot access an instance variable of a class from an inner class directly. Think a little bit about it; how would an instance of class B know which instance of class A to use to read the value of variable x?

In order to access it, you need to provide an instance of class A to the ctor of B. Another means of doing this (if it suits your scenarios) would be to make x static, but I would not suggest it generally.

For an example see this:

class A
{
  int x;
  List<B> list;

  class B
  {
    B(A instance)
    {
      // Access x here using A.x;
    }
  }

  public void AddToList()
  {
     list.Add(new B(this));
  }
}
Savvas Kleanthous
  • 2,695
  • 17
  • 18
  • To be fair, people coming to C# from Java would expect this to work, because the language maintains this reference implicitly by default (i.e. non-static nested classes). I.e. when you ask "how would an instance of class B know which instance of class A to use", in Java it knows because that instance of class A is determined when the class B instance is instantiated using that instance of class A. C# doesn't do it that way (and I'm glad for that), but it _could_. – Peter Duniho Dec 01 '14 at 23:34