user310291
user310291

Reputation: 38228

Something weird in Visual Studio Debugger

I have some class with private member _stuffs which is of type IStuffs an interface.

When I set a break point just before getting out of the constructor, when debugging and watching the variable at the break point, local variable _stuffs is not null (filled with MyStuffs Object) whereas this._stuffs is null and when back in caller instance MyModelApp._stuffs stays null. Why it is not set with MyStuffs Object ?

public class MyModelApp : ModelApp, IModelApp
{

   private App _parent;

   private IStuffs _stuffs;

   public MyModelApp(object parent)
      : base(parent)
   {
      IStuffs _stuffs = new MyStuffs(this);

      // Break point here
   }    
}

Upvotes: 0

Views: 71

Answers (3)

Cyral
Cyral

Reputation: 14153

You are creating _stuffs as a new local variable, and not as the private IStuffs _stuffs, which has global scope. I assume you mean to assign new MyStuffs(this); to the global field _stuffs instead of creating an entire new object, because currently you have two different variables, but you are getting confused becaus they have the same name.

private IStuffs _stuffs;

public MyModelApp(object parent)
  : base(parent)
{
   _stuffs = new MyStuffs(this);
} 

The above is the correct way, creating a new MyStuffs object as the variable in the global scope rather than the local scope.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503090

Look carefully at your constructor:

public MyModelApp(object parent)
   : base(parent)
{
   IStuffs _stuffs = new MyStuffs(this);
}

You're declaring a local variable called _stuffs and giving it a value. That is not the same as the field _stuffs. I strongly suspect that you don't want a local variable - you just want to initialize the field instead:

public MyModelApp(object parent)
   : base(parent)
{
   _stuffs = new MyStuffs(this);
}

Upvotes: 2

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

Do you realize you're actually assigning to local variable and not to instance variable?

private IStuffs _stuffs;

public MyModelApp(object parent)
: base(parent)
{
    IStuffs _stuffs = new MyStuffs(this);//This is a local variable

    //If you need local variable also here, just rename it
    //or use this qualifier

    this._stuffs = new MyStuffs(this);
}

Upvotes: 3

Related Questions