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
  • 11,948
  • 11
  • 47
  • 68
Saddy
  • 313
  • 4
  • 22

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
  • 47,018
  • 22
  • 121
  • 208
3

To fix the problem you can chnage the following

f=f;

to

this.f = f;

3dd
  • 2,520
  • 13
  • 20
0

You have to assgined a Foo obejct like

        Foo f;
        public Inner(Foo _f)
        {
            f = _f;
        }
Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70