30 April 2007

Format Strings -- Episode Two

Last time I wrote about using string.Format as you type. What if you already have some code and want to transform it to string.Format?

    public override string ToString()
    {
      return "Folder: '" + myPath + "'";
    }

When you position caret inside such string expression, ReSharper displays light bulb and suggests few context actions (caret was on myPath in this case):



It is not surprizing that the first item in menu does what we want:

    public override string ToString()
    {
      return string.Format("Folder: '{0}'", myPath);
    }

If there is known method overload that fits format style, it will be used instead of creating extra string.Format call:

    public void Write(StreamWriter writer)
    {
      writer.Write("Folder: '" + myPath + "'");
    }

ReSharper converts it to:

    public void Write(StreamWriter writer)
    {
      writer.Write("Folder: '{0}'", myPath);
    }


Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

27 April 2007

Transforming Conditionals

Testing conditions is at least 50% of code in a typical program. When developer writes code, he not always knows in advance how method will look like at the end. Let's look at some typical cases.

This one is pretty simple method, which takes care of null object:

    public string ConvertToString(object obj)
    {
      if (obj != null)
        return obj.ToString();
 
      return null;
    }

Then I decided to add special handling for IConvertible:

    public string ConvertToString(object obj)
    {
      if (obj != null)
      {
        IConvertible convertible = obj as IConvertible;
        if (convertible != null)
          return Convert.ToString(convertible);
 
        return obj.ToString();
      }
      return null;
    }

Now it seems that it would have been better idea to check and return null immediately instead of placing all the code in the block. How can we fix this? I put caret on an "if" keyword and hit Alt-Enter.



After context action is executed I get what I need:

    public string ConvertToString(object obj)
    {
      if (obj == null)
        return null;
      IConvertible convertible = obj as IConvertible;
      if (convertible != null)
        return Convert.ToString(convertible);
 
      return obj.ToString();
    }

If you like shorter methods, you can further transform the code:



Accepting convertion to conditional makes it even smaller:

    public string ConvertToString(object obj)
    {
      if (obj == null)
        return null;
      IConvertible convertible = obj as IConvertible;
      return convertible != null ? Convert.ToString(convertible) : obj.ToString();
    }



Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

Highlight Usages Of What?

Many people know about Find Usages (default shortcut Alt-F7), which find usages of element under caret. Some people known about Highlight Usages (default shortcut Ctrl-Shift-F7), which places highlighting markers in current file on element usages. However, ReSharper can highlight usages of different things as well.

Usages of Namespaces
Position caret on "using" directive (Imports in Visual Basic) and invoke Highlight Usages command. ReSharper will highlight all symbols which depend on namespace in question.

Usages of Expressions
Select expression in code and invoke Highlight Usages command. ReSharper will highlight same expressions in other places in code.

Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

24 April 2007

Jedi Way -- Implementing Members

Object-oriented program is easy to read, if written properly. At every point you deal with appropriate level of abstractness and you don't have to deal with implementation specific details most of the time. However, when you have large type hierarchies and you are going to modify some aspect of a top level interface -- you may be in trouble. You have to thoroughly investigate all implementing types and provide method body for each one. ReSharper can help, of course.

Jedi Trick Level 1
Invoke Type Hierarchy and select Derived Types in the toolbar. You will see hierarchy of types derived from the interface. Use "Go To Next/Previous Occurence" command (Ctrl-Alt-Down/Up) to navigate between types. As soon as you have type which requires implementation in the code editor, Code Analysis will show red squiggly. Invoke Quick Fix to implement member and type in method body.

Jedi Trick Level 2
Use Context Action's power to implement members. Position caret on the newely created member, IsAvailable in this case. You will see the light saber bulb which is activated with Alt-Enter. Select "Implement member" and you will be prompted with the list of types. You can select "All above types" and get method body throwing NotImplementedException for every type.

Jedi Trick Level 3
Use Quick Fix power to implement members. Type in method body right in the interface, as if it were implementation. Code Analysis will show red squiggly, because interface member cannot have body. But you will also get two Quick Fixes via red light bulb - remove method body or use body for implementations. As soon as you select second one, body will be copied to appropriate implementations and removed from interface.

Jedi Trick Level 4
Available to Yoda only.

Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

Format Strings -- Episode One

Are you going to override ToString? You do this from time to time, definitely.



You begin typing format string and immediately see ReSharper coming to rescue in an absolutely non-invasive way. First the light bulb will appear.



Second, you hit Alt-Enter to see the list of available context actions. Only one is available here, but it is exactly the one we need.



Accept it with Enter and you can start typing arguments.



Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

Customizing ReSharper Colors

Sometimes people complain that they don't like ReSharper's colors, or default colors do not math their personal scheme, or identifier highlighting gets too much in the way. Luckily, you can configure colors.
Color configuration for ReSharper items can be changed in the Visual Studio Options (Tools Options menu), in the Fonts and Colors section. Select "Text Editor" in the settings combobox and scroll down to "Resharper" items. You will see color and font settings for identifiers of different kinds, error and warning highlighting, navigation targets, read/write usages and much more.

20 April 2007

The Horizon Comes Closer

It's been a while since I last wrote about ReSharper future. That's because we are actively working on ReSharper 3.0, the upcoming new version of our intelligent Visual Studio add-in. Besides numerous bug fixes, improvements and greater performance, we are adding more functionality to our product. In the upcoming posts I'm going to reveal what is going to be included in ReSharper 3.0 in more detail. Now I'll just list the most important things we are planning for this release:

Visual Basic .NET
C# developers already know how fast one can work with source code when ReSharper is installed. Now we bring the same pleasure to VB.NET developers. Editor improvements, such as expand/collapse selection, navigate next/prev member, duplicate line, comment/uncomment block/line and other small features, make code editing more enjoyable. Completion brings Smart Completion and Type Completion flavors to VB.NET along with automatic Imports inserting and all other bells and whistles. Code generation with Alt-Ins provides a quick means for generating properties, constructors, overriding and implementing members and works with the same level of cleverness as it does in C#. Live Templates now understand VB.NET and have smart iteration and cast templates, such as For Each or TryCast. Of course, we have Refactoring support for VB.NET in this version, which includes the most important refactorings like Rename, Move and Copy Type, Change Signature, Introduct and Inline Variable, and many others.

If you are a VB.NET developer and if you've ever seen how fast ReSharper-powered C# developers work, you owe yourself to try our EAP versions of ReSharper 3.0.

XML support
We are adding a number of useful editor improvements to Visual Studio XML support. They include expand selection, navigate to next/previous tag, replace tags, and some others. Live Templates are now supported in XML files and have some useful macros. Type completion works in XML, so that you can write configuration files easier. You can also navigate to type from XML.

XAML support
Being a language for user interface definition, it is still a compilation unit and it defines types and fields which are visible from other code. ReSharper is now capable of parsing XAML files, navigating, searching, and otherwise providing data for code exploration tools. We also plan to support smart completion and type completion in specific places, like event handlers, namespace aliases and tags/attributes where a control type is expected. Refactoring support in XAML will be limited in this version, but will allow renaming and moving types between namespaces without breaking code.

Tools
Besides all the languages support listed above, we are adding a number of useful tools and upgrading some existing tools. We've included To-do Explorer, which hunts for comments according to specified patterns and displays them in a dedicated tool window for quick access. We've improved Type Hierarchy to show members of selected type, either all or just polymorphic, and added some new hierarchy browsing capabilities. Unit Testing system is undergoing a major update to support multiple sessions, better support for various testing frameworks like mbUnit, VSTS and NSpecify, improved debugging usability and allow browsing solution for tests in dedicated Unit Test Explorer tool window. The "Go to by name" family of features, which already includes Go To Type, File or File member, is supplemented with Go To Symbol - your best friend when you remember a method's name, but not that util class it was seen in.

Improvements and bug fixes
I'm not going to give you a list of hundreds of bugs and exceptions fixed since previous release. I can't even remember all those small improvements here and there, which makes development with ReSharper even smoother and helps support development flow. Numerous context actions help craft code faster in many new use cases. New code analysis helps keep code clean and spot various problems as soon as you create them (accidentaly, of course). New quick fixes provide yet more automatic code corrections.

What next?
I'm going to blog in details about some of the new features in ReSharper 3.0 and show you some screen casts. I will probably break announced rules of this blog and start publishing tips and tricks, combos and advanced techniques in code generation, analysis and refactoring.

Stay tuned!