0

I have a class called Foo, it has an inner class Inner. The Inner class has reference to outer class's field.

public class Foo
{
    int foo = 2;

    public class Inner
    {
        Foo f;
        public Inner(Foo f)
        {
            f=f;
        }

        public override String ToString()
        {
            return "Inner[foo="+f.foo+"]" ;
        }
    }
}

This is my program.

public class Program
{
   public static void Main(string[] args)
   {    
      Foo foo=new Foo();
      Foo.Inner inner=new Foo.Inner(foo);
      Console.WriteLine(inner.ToString());
   }
}

There is no problem to compile it, but it fails when I run it. It gives me an exception

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Foo.Inner.ToString()

What is going on here?

Uriil
  • 10,970
  • 8
  • 45
  • 67
Saddy
  • 303
  • 4
  • 19

3 Answers3

6

Problem:
Your problem is in doing f = f. It is not doing anything productive. This line does not update the Inner field f and it remains unassigned or null. So when you do Console.WriteLine(inner.ToString());, it throws error at "Inner[foo=" + f.foo + "]"

Also VS shows a warning

enter image description here

Solution:
1. Change constructor variable to something else. Like this

Foo f;
public Inner(Foo f1)
{
    f = f1;
}


OR
2. Add this to distinguish between variables.

Foo f;
public Inner(Foo f)
{
    this.f = f;
}
Nikhil Agrawal
  • 44,717
  • 22
  • 115
  • 201
3

To fix the problem you can chnage the following

f=f;

to

this.f = f;

3dd
  • 2,500
  • 12
  • 20
0

You have to assgined a Foo obejct like

        Foo f;
        public Inner(Foo _f)
        {
            f = _f;
        }
Dhaval Patel
  • 7,315
  • 6
  • 35
  • 68