web analytics

How to implemente a method that returns a disposable object in C#?

Options

codeling 1595 - 6639
@2016-01-13 21:03:08

The following example desmonstrates how to implementing a method that returns a disposable object by using a try/finally block without a catch block and how way allows exceptions to be raised at the fault point and make sure that object is disposed.

In the following OpenPort1 method, the call to open the ISerializable object SerialPort or the call to SomeMethod can fail. A warning of "the object is not disposed before all references to the object are out of scope" is raised on this implementation.

public SerialPort OpenPort1(string portName)
{
   SerialPort port = new SerialPort(portName);
   port.Open();  //this might throw
   SomeMethod(); //Other method operations can fail
   return port;
}

In the following OpenPort2 method, two SerialPort objects are declared and set to null:

  • tempPort, which is used to test that the method operations succeed.
  • port, which is used for the return value of the method.

The tempPort is constructed and opened in a try block, and any other required work is performed in the same try block. At the end of the try block, the opened port is assigned to the port object that will be returned and the tempPort object is set to null.

The finally block checks the value of tempPort. If it is not null, an operation in the method has failed, and tempPort is closed to make sure that any resources are released. The returned port object will contain the opened SerialPort object if the operations of the method succeeded, or it will be null if an operation failed.

public SerialPort OpenPort2(string portName)
{
   SerialPort tempPort = null;
   SerialPort port = null;
   try
   {
      tempPort = new SerialPort(portName);
      tempPort.Open();
      SomeMethod();
      //Add any other methods above this line
      port = tempPort;
      tempPort = null;
   }
   finally
   {
      if (tempPort != null)
      {
         tempPort.Close();
      }
   }
   return port;
}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com