Monday, February 22, 2016

Visual Studio Shortcuts: Implementing the Dispose Pattern

I'm a big fan of the shortcuts that Visual Studio offers to make things easier as a developer. Sometimes these simply save us some typing. But sometimes, they can help us implement a difficult pattern. In this case, Visual Studio 2015 helps us implement the Dispose pattern.

Implementing the IDisposable Interface
Using Visual Studio, we can easily implement the IDisposable interface just like we implement any other interface.

First, we'll create a class and specify that we want to implement IDisposable:

Then we can put our cursor on "IDisposable" and press "Ctrl+." (or click on the light bulb in Visual Studio 2015). This gives us a popup that offers to "Implement interface" for us:

If we chose this, the results are pretty unimpressive:

This is because the "IDisposable" interface only has a single method: "Dispose". But if we actually want to implement the Dispose pattern, things get much more complicated.

You can see how complicated by looking at various MSDN articles (IDisposable Interface and Dispose Pattern) and lots of other articles and questions on StackOverflow.

The "Implement interface" option has been around for a while, and I use it all the time. It's very useful. But it's not very useful in helping us get "IDisposable" right.

Fortunately, Visual Studio 2015 gives us a really cool option to make this easier.

Implementing the Dispose Pattern
The additional option that we get is "Implement interface with Dispose pattern":

This option is new in Visual Studio 2015 (sorry, it's not available in earlier versions of Visual Studio, but it *is* available in all editions of Visual Studio 2015, including the Community Edition).

This gives us quite a bit more code:

This takes care of most of the hard bits for us, and it gives us some really useful comments to help us get our code in the right place.

So if we need to implement the Dispose pattern in a class, we can use this option to give us the shell of the code, fill in the TODOs that we have, and then remove the elements that we don't need.

Wrap Up
Visual Studio has been one of the best IDEs out there for a long time. A big part of that is that it includes many shortcuts to make our coding faster and easier. In addition, we keep getting new, unexpected features.

Whenever I point out this particular shortcut, the response has been "I didn't know that was there!" Usually followed up with "That's really awesome!" And that was my initial reaction -- I ran across this feature completely by accident when I was implementing the IDisposable interface the hard way.

It's always good to explore our tools to see what options are out there. Sometimes we run across really cool things. In this case, we get code that helps us "fall into the pit of success" when we're implementing one of the more complicated patterns out there.

Happy Coding!

No comments:

Post a Comment