-2

Why does the the object ok go out of scope when used in the if statement? and how can I dispose of object ok?

public class hello : IDisposable { 

}

public class hi{

    private void b() 
    {
        using(hello ok = new hello());

        hello no = new hello();

        if( ok == no )
        {
            ok = no;
        }
    }
}
H H
  • 263,252
  • 30
  • 330
  • 514
Mark
  • 209
  • 1
  • 5
  • 13

1 Answers1

2

You are not using the using statement correctly, what you want is as follows:

using(hello ok = new hello())
{
    hello no = new hello();

    if( ok == no )//Point 1
    {
        ok = no;//Point 2
    }
}//Point 3

Some points (as found in comments above):

  1. This will never be true, because you have two difference instances. Unless, the class has overridden the equality operator

  2. This is not valid and will not compile, you cannot re-assign a variable used in a using statement

  3. Here ok will go out of scope, it will also be disposed at this point, assuming it implements IDisposible - I think that it will not compile if it doesn't implement IDisposable anyway

Overall, what you are seemingly trying to do doesn't make much sense at all.

musefan
  • 47,875
  • 21
  • 135
  • 185