CA2000 with nested constructors

Me again with another CA2000 warning.

The following code generates the CA2000 warning:

// Use an emulated GPS device
nmeaInterpreter.Start(new VirtualDevice(new NmeaEmulator()));

The following warning occurs:

CA2000 : Microsoft.Reliability : In method 'GpsService.Start()', call System.IDisposable.Dispose on object 'new NmeaEmulator()' before all references to it are out of scope.

I have already checked over Microsoft's documentation on CA2000, but couldn't find a good example of how to deal with nested constructors. Obviously I don't want to store a reference myself to the emulator. I want the reference to only be passed to the constructor.

Is C# creating a temporary object under the hood which I need to dispose?


Is C# creating a temporary object under the hood which I need to dispose?

Yes, any time you use the new operator, a new object is created. Generally you can rely on the garbage collector to handle this type of thing for you, but CA2000 is alerting you to the fact that the object you created implements the IDisposable interface, and you should therefore call the Dispose method to ensure that any unmanaged resources it uses get properly released.

Nesting object creation like this in calls to constructors is somewhat dangerous, as the documentation describes, because if the construction of one of the objects was to fail, there would be no way to ensure that the nested object was properly disposed.

I'm not really sure why you're using this pattern to begin with. The VirtualDevice class should be solely responsible for managing the lifetime of the objects it creates. All that the GpsService.Start() method should have to do (or know about!) is create a VirtualDevice object. That object should, in turn, create whatever nested objects it needs, which it can subsequently ensure are properly disposed.

Need Your Help

Subversion for web development

svn apache htdocs

I've read a lot of articles about Subversion and pushing the information to a web server, but I'm still having difficulties.

Why doesn't it find my beacons?

ios bluetooth-lowenergy ibeacon

I am writing both Android and iOS apps which need to find BLE beacons around the device.