Going generic

This How-To explains how to take advantage of ReSharper’s features to quickly convert your arrays into generic collections.

In .NET 1.1, if you wanted to have some typed interface to return some items, your only choice was to use arrays, since collections were untyped:

In .NET 1.1 you had to use arrays

If the implementation of INode did not keep an array of subnodes, one had to allocate a fresh array on every GetSubNodes() call.

In .NET 2.0, however, one can use generic collections. We would aim for our interface to look like this:

Generic collections are available in .NET 2.0

Generic collections a very good thing for a whole number of reasons that we won’t get into here.

So, now that people are migrating from 1.1 to 2.0, it would be great to somehow convert legacy interfaces from arrays to collections. For this, ReSharper comes in extremely handy. We ourselves used the following procedure when developing ReSharper 2.0 and we think it can be useful to you, too.

  1. Invoke the Change Signature refactoring (keyboard shortcut Ctrl + F6) on INode.GetSubNodes() to change the return type from INode to IList<INode>:

    Change Signature refactoring

    The return type of all implementations is changed accordingly.

  2. After you compile, the code will, of course, contain errors such as this one:

    Cannot convert IList<INode> to INode[]

    You can identify these compilation errors and navigate to them by using the error stripes on the right-hand sidebar:

    You can see all the errors and warnings and go to them.

          TIP:  You can also navigate between compilation errors in the file by using keyboard only. Press F12 to go the next error and Shift+F12 to go to the previous error.

    So, for errors like the one shown above, ReSharper suggests a quick-fix (keyboard shortcut Alt + Enter) to help you change the type of ‘subNodes‘ to IList:

    This quick-fix from ReSharper solves the problem

  3. However, another kind of error remains: the ‘Length’ member should be changed to ‘Count’ everywhere:

    We need to change all Lengths to Counts

    Just use the Change All quick-fix to quickly change all ‘Length‘s into ‘Count‘s:

    Lengths are changed to Counts with this quick-fix

    ReSharper will suggest a list of members and, in this case, will automatically guess that Count should be the right member.

    This concludes our conversion.



So, if you are going generic, we suggest you save yourself some hassle and give ReSharper a try!

Read more about the features discussed in this How-To:
Refactoring
Error Highlighting and Quick-Fixes

This entry was posted in How-To's and tagged . Bookmark the permalink.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>