C# setting members from using statement

84 Views Asked by At
class A
{
  TypeX PropertyX;

  void SomeMethod()
  {
    using (DisposableType y = new DisposableType())
    {
      PropertyX = y.GetX();
    }
  }
}

What happens to PropertyX when Y is being disposed? Would I rather do this, if I don't know what is being disposed with Y?

class A : IDisposable
{
  TypeX PropertyX { get; set;}
  DisposableType Y { get; set; }

  void SomeMethod()
  {
    using (Y = new DisposableType())
    {
      PropertyX = Y.GetX();
    }
  }

 void Dispose()
 {
   Y.Dispose();
 }

}
1

There are 1 best solutions below

5
emt On

EDIT: OP changed the question

Your MainWindow will not get disposed, but automation instance will get disposed after the execution leaves using block. Another way to write this would be:

    using var automation = new UIA2Automation();
    MainWindow = launcher.App.GetMainWindow(automation);

A more verbose way to write the same thing would be:

    var automation = new UIA2Automation();
    MainWindow = launcher.App.GetMainWindow(automation);
    
    // At this point MainWindow is already instantiated.
    // We no longer need automation instance so we dispose of it.
    automation.Dispose();

Quick Google search lead me to FlaUI project and it looks like it is what you are using. Looking at the code samples, it looks like your approach is the correct one.