Question

I'm wondering what (and if it's defined) the behavior is if i need to re instanciate a variable within it's own using() tag?

I have an actual use case for this, using SharpDX i have variables that i want declared outside the render loop (used for each frame) that i'd ideally wrap as this using(thevariable){MainLoop{}}; However if something happens (the user resizes) that variable may need to be disposed & reinitialized. I see in the samples it's being initialized to null & then re initialized within the loop if needed, re disposed, and then disposed of again after the loop which looks a lot worse than using well, using statements so i was wondering what would be the behavior of code such as this:

void Main()
{
    using(var MyDisposable = new MyDisposable())
    {
        If(SomeCondition)
        {
             MyDisposable.Dispose() // Do i need to call this? Or is it auto called thanks to using when leaving the block? What will using call dispose on, the object that MyDisposable refers to, or the one it refered to back when i called the using statement?
             MyDisposable = new MyDisposable(); // Is this going to be managed by the using block? Is this even valid?
        }
    }
}

Also I'm not sure if the behavior changed over time, I'm assuming not but if it did I'm interested in .net 4.5 answers

Was it helpful?

Solution

I think you'll find that this results in a compiler error.. specifically:

Cannot assign to 'MyDisposable' because it is a 'using variable'

So, the answer to your question is: Nothing happens in this instance. Your code won't compile.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top