Using ‘using’ with Phidget’s C# Library

The [`using`](http://msdn.microsoft.com/en-us/library/yh598w02.aspx) statement is an extremely useful feature of C# and it’s quite disappointing that Phidgets did not implement [`IDisposable`](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx). Thankfully it’s fairly easy to create a wrapper for any Phidget that implements it so we can simply some code.

public class PhidgetWrapper : 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())
{
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](/wp-content/uploads/2011/02/PhidgetWrapperExample.cs).

One Reply to “Using ‘using’ with Phidget’s C# Library”

Leave a Reply

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