Using ‘using’ with Phidget’s C# Library

The using statement is an extremely useful feature of C# and it's quite disappointing that Phidgets did not implement IDisposable. Thankfully it's fairly easy to create a wrapper for any Phidget that implements it so we can simply some code.

public class PhidgetWrapper<TPhidget> : IDisposable
  where TPhidget : Phidget, new()
{
  public TPhidget Phidget { get; private set; }

  public PhidgetWrapper()
  {
    Phidget = new TPhidget();
    Phidget.open();
  }

  public void Dispose()
  {
    Phidget.close();
  }
}

And using it is simple.

using System;
using Phidgets;

public class Example
{
  public static void Main()
  {
    using(var interfaceKitWrapper = new PhidgetWrapper<InterfaceKit>())
    {
      var interfaceKit = interfaceKitWrapper.Phidget;

      Console.WriteLine("Waiting for InterfaceKit to be attached...");
      interfaceKit.waitForAttachment();

      Console.WriteLine("InterfaceKit attached: serial={0}",
        interfaceKit.SerialNumber);
    }
  }
}

You can find the source for the wrapper and the sample here.

Join the conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *