views:

54

answers:

1

I'm writing a wrapper class in C# for a USB device (using P/Invoke to communicate with it). The device needs to be sent an open message before use, and a close method when it's done with. In my constructor I want to try to open the device and return null if that call fails for whatever reason. I'll also write a Dispose() which calls the close method on the device.

Is this a sensible way to code it? Or should I have a separate ConnectToDevice method?

By putting it in the constructor I hope users of my class can simply write:

USBDevice myDevice = new USBDevice()

if (myDevice != null) {
  myDevice.PerformAction();
  myDevice.Dispose();
  myDevice = null;
}
+2  A: 

If your constructor fails the reference will always be null. However, if you have allocated some disposable resources prior to the error, the caller can't call Dispose on the instance since he has no reference to it. Thus, if you want to do this in the constructor, you need to make sure the constructor fails gracefully.

To keep things simple, I would probably go with a Connect method instead.

Brian Rasmussen