Archive for the ‘How-To's’ Category

A Quick Update on Issues and Workarounds

Tuesday, June 29th, 2010

Users keep coming with questions whether a particular issue that they encounter in Visual Studio is related to ReSharper. Well, some of them are, some of them aren’t. Either way, we try our best to provide info on workarounds for common issues, both our own and external, in this blog post. Check it out for latest updates on GetTempFileName()-related exceptions in certain versions of Windows, and “insufficient memory” messages caused by simple cut-and-paste operations in Visual Studio — both issues fortunately not in any way related to ReSharper.

As to ReSharper’s own issues, we keep fixing them in 5.1 Nightly Builds, hoping to provide the official 5.1 bug fix update really soon. If you happen to find stop-shipping bugs in the nightly builds, hurry up to report them!

Sample SSR Pattern Catalog Available for Download

Wednesday, June 2nd, 2010

A while ago we introduced Structural Search and Replace, a new powerful feature in ReSharper 5 that lets you search for custom code patterns and replace them with other patterns, facilitating batch removal (or improvement) of stinky code.

We were hoping to include a set of ready-to-use search and replace patterns into ReSharper 5.0 release but it just didn’t happen. Instead, we’re publishing a sample Pattern Catalog on the web site for you to download.

The sample Pattern Catalog currently contains 17 patterns to search for and replace unreachable code, redundant compound assignments, clumsy method chains, and other pieces of code that you’d better get rid of.

As soon as you’ve downloaded and unzipped the Pattern Catalog, do the following to import it:

  1. In Visual Studio, choose ReSharper | Tools | Pattern Catalog.
  2. Click Import and select the XML file that contains the sample Pattern Catalog.

JetBrains Vendor Session at DevConnections Now Available

Thursday, May 20th, 2010

We’ve recently received a recording from JetBrains vendor session at DevConnections hosted by our wonderful evangelist, Hadi Hariri. A certainly good thing about the performance is that instead of handing out a bunch of free licenses worth a new Rolls-Royce Phantom, he was rather doing business, showing how you can use the combination of TDD, MSpec and ReSharper to create ASP.NET MVC applications efficiently. If you weren’t attending DevConnections but you’re interested in TDD, MSpec and ASP.NET MVC, here’s the full performance:

In addition to vimeo, we’ll put the video on the website shortly to make it available from the ReSharper section.

ReSharper 5.0: Known Issues, Workarounds, and Bugfix Schedule

Tuesday, May 4th, 2010

Hello everyone! Hope you’re having a good time using the new ReSharper 5.0. If you do, just ignore this post :)

If you’re facing issues with ReSharper 5.0, read on. There are certain bugs, usability problems and otherwise weird behavior that users report following the release (surprise!). Some of them you can work around, others you can’t, but both kinds of issues will be addressed in the upcoming ReSharper 5.1. It’s scheduled for release in June but we’ll open the Early Access Program in May, and chances are that the most annoying issues will be fixed in these early builds.

Here are some of the most annoying issues that have known workarounds:

  • RSRP-178681: aspx pages lose references to their code-behind files. A lot of people complained that when saving an aspx page with a code-behind file, the reference to the code behind file gets lost and lots of errors start to pop up.

    Workaround: Go back to the aspx page and save it again (without changing anything): the reference restores and both files display and work correctly.
  • RSRP-178492: Adding Cyrillic comments and creating new custom controls in WPF applications sometimes changes file encoding from UTF-8 to Win-1251.

    Workaround: The only way to change this behavior is to manually roll file encoding back to UTF-8 by choosing File | Advanced Save Options in Visual Studio.
  • Another problem reported in RSRP-178492 is that during refactorings, ReSharper changes the locale of XAML files based on your Windows locale. That only happens if you don’t select the “To enable Undo, open all files with changes for editing” check box in a refactoring dialog box.

    Workaround: Make sure to select the “To enable Undo, open all files with changes for editing” check box.
  • UPDATE! Thanks to Frans Bouma for reminding about the other annoying issue, NP-20: Splitting a Visual Studio text editor tab makes ReSharper marker bar and possibly other features go away in one or both parts of this particular tab.

    Workaround: Rejoin the editor tab, close it, then reopen.
  • UPDATE 2! Visual Studio 2010 crashes during file save and build operations.

    Workaround: ReSharper may cause this problem but there’s a known common cause of this behavior: a certain version of AnkhSvn. If you have both ReSharper and AnkhSvn installed, try following Microsoft guidelines on updating your AnkhSvn build. Builds 2.1.8420 and higher are reported to fix the intermittent Visual Studio crash problem.
  • UPDATE 3a! RSRP-147892: Calling GetTempFileName() in Windows 7 or in Windows Server 2008 R2 causes UnauthorizedAccessException

    Workaround: This is not a ReSharper problem. Microsoft has confirmed that this issue occurs because the GetTempFileName() function in Windows 7 and Windows Server 2008 R2 handles a duplicated file name incorrectly. Download this Microsoft hot fix to remove the issue.
  • UPDATE 3b! Even small cut-and-paste operations raise “insufficient memory” errors in Visual Studio 2010.

    Workaround: Again, this is not a ReSharper issue. Microsoft has released a patch for Visual Studio 2010 that removes this issue. For details on its symptoms and other implications, read this Visual Studio blog post.

We also receive reports about performance issues when renaming and doing Find Usages in large projects that contain aspx files. We are doing performance analysis and aiming to solve these issues in time for the bug fix release.

Just in case you’re interested, here’s the full list of issues currently scheduled for ReSharper 5.1.

On a different note, people report on a regular basis about Visual Studio 2005 or 2008 installations that freeze or crash after opening web forms, or Solution Explorer that hangs up. There are known solutions to this kind of issues (not having anything to do with ReSharper), including:

Before you contact us with such issues suspecting ReSharper, please make sure to try the solutions provided above.

By the way, if you’re using Visual Studio 2010, have you installed Windows Automation API? Rumors say it really boosts Visual Studio performance, particularly with ReSharper.

Introducing ReSharper 5.0: Structural Search and Replace

Wednesday, April 7th, 2010

Previous posts introducing ReSharper 5.0:

Structural Search and Replace is one of the most powerful yet less explored ReSharper 5.0 features. It allows you to find code that matches a structured template, parts of which may have certain restrictions. For example, you can set the type of the expression you are looking for, or specify the number of arguments. In addition to plainly finding parts of code that match the template, you can instantly replace them using an equally powerful replace template, or even configure ReSharper to inspect your solution for code that matches the search pattern and suggest replacing it using a quick-fix. Simply put, Structural Search and Replace provides you with an opportunity to easily extend built-in ReSharper code inspections with your custom ones.

Smart Search

Let’s look at a specific example. We’ll search for all expressions matching the pattern enumerable.Count() > 0, where enumerable is any expression of type IEnumerable.

If you were to solve this task with Find Usages, you would step through all the calls of the Count() method. This means you would have to go through tens or hundreds of calls, which is tiring and prone to error. Find Text might look slightly more promising, but once you think about it, problems come up too:

  1. The expression may be written with line returns or comments.
  2. The Count() method in your project may be implemented by objects of different types.

Find Text doesn’t cut it either.

Choose ReSharper | Find | Search With Pattern and enter the following pattern in the text box:

   $enumerable$.Count() > 0

The $enumerable$ string will be highlighted red. This is because dollar signs signify placeholders — a placeholder is replaced with any text matching the specified restrictions: the placeholder type and its parameters. In our case, $enumerable$ will match any expression of type IEnumerable. We must define this placeholder by clicking Add Placeholder, selecting Expression and entering “enumerable” in the Name field (the placeholder name without the dollar signs). For Expression Type enter “IEnumerable” (just start typing and ReSharper will suggest suitable options). Make sure to check Or derived type as well.

So, in just a few seconds, without even going near regular expressions we’ve created an effective search pattern. But here’s another feature that’s extra-useful! Note the Match similar constructs check box below the edit field. If you select it, ReSharper will search not only for exact matches but also for constructs that are semantically identical. For example, a > 0 and 0 < a are semantically identical. In our case, you should probably select this check box, because you’re likely to be looking for all the different conditional statements where Count() is compared with zero.

That’s all! Now click Find and see the results.

Smart Replace

A search feature this powerful would not be nearly as useful without a replace feature. You don’t want to just locate all the bad code — you want to replace it with good code! So, go ahead and click Replace in the Search With Pattern dialog. You will get a box to enter the replace pattern. The replace pattern can be any text that is valid for the language you’re using, plus placeholders if you need them. For example, enter the following:

$enumerable$.Any()

And click Replace!

Turn a Pattern into a Highlighting and a Quick-Fix

Now you have a search template and a replace pattern. It makes sense to create a highlighting and a quick-fix based on these patterns. To do so, click Save in the pattern editing dialog, and your pattern will be saved to the Pattern Catalog. This catalog is used to store commonly used patterns, and may turn into a powerful tool for creating your own code inspections.

If you open the catalog (ReSharper | Tools | Pattern Catalog), you can define a tooltip for your pattern, which will pop up in the corresponding quick-fix, as well as the type of highlighting you want to apply:

Once you set these options for your pattern, the highlighting works! Now all code that matches your pattern will be highlighted — on the fly. Also, the appropriate quick-fix will appear as soon as you position the caret on the highlighted expression. Ain’t it cool?!

Search Pattern Examples

This search pattern is designed to simplify expressions:

In this example we used placeholders for the types of the expression and the identifier. We didn’t impose any restrictions on them, but used them in the replace pattern. The only placeholder with restrictions is $seq$ — it’s an IEnumerable.

And here’s a pattern that implements highlighting and a quick-fix for Replace ‘if’ with ‘?:’:

Sharing Patterns

If you have created a useful search and replace pattern that detects and removes a code smell, share your knowledge with colleagues using import/export functionality in the the Pattern Catalog! As an option, leave comments with your patterns, and with your permission, we may include the most interesting patterns in the next version of ReSharper!

UPDATE! A sample Pattern Catalog is now available from the ReSharper web site. Learn details in this blog post.

Author: Alexander Zverev, senior ReSharper developer. Translated from original article (in Russian)

Introducing ReSharper 5.0: Value Tracking

Monday, March 29th, 2010

Previous posts introducing ReSharper 5.0:

Recently we posted about Call Tracking, which is a new feature in ReSharper 5.0.

A logical next step from Call Tracking is Value Tracking. Value Tracking is designed to help you determine how a certain incorrect value might have passed to a given point in your program, and where it might be passed next. This helps you investigate possible NullReferenceExceptions, inappropriate behavior and reasons why you get incorrect values.

You can call Value Tracking by choosing ReSharper | Inspect | Value Origin or ReSharper | Inspect | Value Destination over a local variable, parameter, or another kind of value, and you can also use a new shortcut to Call Tracking, Value Tracking, and Type Hierarchy: Inspect This (Ctrl+Shift+Alt+A).

Without theorizing too much, I will review some use cases and scenarios where Value Tracking is useful.

A Basic Example

In this example, a NullReferenceException is thrown in the VisitData method. Let’s determine where the null comes from. Position the caret at the usage of the dc parameter in VisitData and run the analysis (ReSharper | Inspect | Value Origin):


    public class Main
    {
      void Start()
      {
        Console.WriteLine(Do(new DataClass()));
      }

      void Start2()
      {
        Console.WriteLine(Do(null));
      }

      int Do(DataClass data)
      {
        var v = new Visitor();
        return v.VisitData(data);
      }
    }

    public class DataClass
    {
      public int GetData()
      {
        return 0;
      }
    }

    public class Visitor
    {
      public int VisitData(DataClass dc)
      {
        return dc.GetData();
      }
    }

If you run the analysis in your own code (using the same example) and try to navigate around the results tree, you will see that it contains all the nodes you might be interested in:

  • Our usage of dc (the place the exception is thrown).
  • The data parameter passed to VisitData
  • A call of Do with “good data” (in the graphic above, the values we need are in bold).
  • A call of Do with the null value – the culprit.

Basically, this is a massive Find Usages. However, Value Tracking:

  • Skips the unimportant steps, thus saving time.
  • Displays values in a convenient way, so you can find the source of your problem without looking through all the symbol usages one by one.

Value Tracking is especially useful if variable names are changed often, or if values are placed in collections or passed via closures. Let’s look at these more complex use cases in more detail.

Inheritance

So we have an interface, its implementation, fields, field initializers, and constructors. Our task is to figure out which values Main.Start can display. Highlight dataProvider.Foo and invoke Value Origin on it (ReSharper | Inspect | Value Origin):


    public interface IInterface
    {
      int Foo();
    }

    public class Base1 : IInterface
    {
      public virtual int Foo()
      {
        return 1;
      }
    }

    public class Base2 : IInterface
    {
      private readonly int _foo = 2;

      public Base2()
      {
      }

      public Base2(int foo)
      {
        this._foo = foo;
      }

      public virtual int Foo()
      {
        return _foo;
      }
    }

    public class Main
    {
      public void Start(IInterface dataProvider)
      {
        Console.WriteLine(dataProvider.Foo());
      }

      public void Usage()
      {
        Start(new Base2(3));
      }
    }


The results of this Value Tracking include:

  • Implementation of Foo that returns the constant 1.
  • Implementation of Foo that returns the value of _foo as well as all value sources of that field:
    • The assignment of a value to the field in the constructor.
    • Call of constructor with parameter = 3.
    • Initializer of the field with value = 2.

Note how in just a few seconds we found all the possible values. Imagine how much time you would save on highly-branched hierarchies and complex logic!

Collections

Now let’s look at working with collections. Let’s identify the set of all values that the following code will print to screen. To do this, position the caret on the usage of i inside Console.WriteLine and run the Value Origin analysis (ReSharper | Inspect | Value Origin):


   class Main
   {
     void Foo()
     {
       var list = new List<int>();
       list.AddRange(GetData());
       list.AddRange(GetDataLazy());
       ModifyData(list);

       foreach (var i in list)
       {
         Console.WriteLine(i);
       }
     }

     void ModifyData(List<int> list)
     {
       list.Add(6);
     }

     private IEnumerable<int> GetData()
     {
       return new[] { 1, 2, 3 };
     }

     IEnumerable<int> GetDataLazy()
     {
       yield return 4;
       yield return 5;
     }
   }

We found an explicit creation of the array, the values that come from the lazy enumerator, and even the Add call. Awesome!

Collections backwards, or where values pass to

Now let’s try going the other direction and see where the number 5 passes. Highlight it and run Value Destination (ReSharper | Inspect | Value Destination):


   public class testMy
   {
     void Do()
     {
       int x = 5;
       var list = Foo(x);

       foreach (var item in list)
       {
         Console.WriteLine(item);
        }
     }

     List<int> Foo(int i)
     {
       var list = new List<int>();
       list.Add(i);
       return list;
     }
   }

We find rather quickly that:

  • 5 is passed to Foo
  • 5 is added to the collection.
  • The collection is returned and used.
  • Collection elements are printed to screen.

Note how, in this and earlier examples, tree nodes are marked with a special pink icon whenever Value Tracking switches from tracking a value to tracking a collection.

Lambdas

Lambdas tend to cause problems, especially if there are many of them or they’re nested. Let’s see how ReSharper handles the following situation. We’re going to track the value paths in both directions:


   public class MyClass
   {
     void Main()
     {
       var checkFunction = GetCheckFunction();
       Console.WriteLine(checkFunction(1));
     }

     Func<Func<int, bool>, int, bool> GetCheckFunction()
     {
       Func<Func<int, bool>, int, bool> myLambda = x =>
                  {
                   Console.WriteLine(x);
                   return x > 100; // this is where we start searching from
                  };
       return myLambda;
     }
   }

First, let’s find out where the values of x come from. Highlight its usage in the Console.WriteLine call and invoke Value Origin (ReSharper | Inspect | Value Origin):

  • We found the lambda that contains the parameter.
  • Next, the analysis tracked where this lambda was passed. Note how all the nodes in which we track the lambda are marked with a special icon.
  • On the last step, we see that the lambda is called with the argument of 1. This is the value of x we’re looking for.

Let’s find out where the value that the lambda returned is used. Highlight x>100 and invoke Value Destination (ReSharper | Inspect | Value Destination):

  • The analysis identifies that the expression is returned when the lambda is executed.
  • Next, ReSharper tracks where the lambda was passed.
  • Finally, we see a WriteLine call that uses the value returned by the lambda.

You can come up with a more complex example using nested lambdas, by replacing the Console.WriteLine call with these two lines:


    Func<Func<int, bool>, int, bool> invocator = (func, i) => func(i);
    Console.WriteLine(invocator (checkFunction,1));

The analysis will still work, and you will easily see where the value of x>100 is passed.

Code that uses nested lambdas is difficult to understand for most people, making this kind of analysis even more useful. You can even try to create a collection of nested lambdas — and it will still work! Go ahead and try it… if you’re into hardcore fun!

Author: Alexander Zverev, senior ReSharper developer. Translated from original article (in Russian)

Introducing ReSharper 5.0: Call Tracking

Wednesday, March 17th, 2010

Previous posts introducing ReSharper 5.0:

There’s a cool new feature in ReSharper 5.0 called Call Tracking (or, alternatively, Call Hierarchy). Basically, it’s a convenient way to perform an all-out Find Usages or Go To Declaration. You can access it by choosing ReSharper | Inspect | Outgoing Calls or ReSharper | Inspect | Incoming Calls.

There’s also Inspect This, a new shortcut to Call Tracking, Value Tracking, and Type Hierarchy features: Ctrl+Shift+Alt+A.

At first we thought of comparing our Call Tracking to Call Hierarchy in Visual Studio 2010. However, it turned out that the VS 2010 version is just not up to par: it doesn’t support events, interfaces, closures and a few other things. It offers no help at all with the use cases we present here. So we’re only going to talk about Call Tracking in ReSharper 5.0.

Events

Let’s search for an outgoing call from Foo (ReSharper | Inspect | Outgoing Calls):


   using System;
   public class C2
   {
     public event EventHandler E = (sender, args) => Subscription_In_Initializer();

     static void Subscription_In_Initializer()
     {
     }

     void Foo()
     {
       E(this, EventArgs.Empty);
     }
   }

   class C3
   {
     void Bar()
     {
       new C2().E += Subscription_In_Method;
     }

     void Subscription_In_Method(object sender, EventArgs e)
     {
     }
   }

Outgoing Call From Foo

Pretty self-explanatory. ReSharper easily finds all subscriptions to E and displays them as possible calls. Nothing too special, but handy for sure.

Generics

Consider this code sample:


   public abstract class Base<T>
   {
     public void Do(T value)
     {
       DoImplementation(value);
     }

     protected abstract void DoImplementation(T value);
   }

   public class Concrete1 : Base<int>
   {
     protected override void DoImplementation(int value)
     {
     }
   }

   public class Concrete2 : Base<string>
   {
     protected override void DoImplementation(string value)
     {
     }
   }

Now let’s look at outgoing calls from Base.Foo:

Outgoing Calls From Do

Speaks for itself.

Now, let’s add a Main class and try searching for outgoing calls from Foo:


   class Main
   {
     void Foo()
     {
       Concrete2 c = null; // null so that we don't clutter the call tree
       c.Do("string");
     }
   }

Outgoing Calls From Foo

Concrete1.DoImplementation doesn’t show up anymore! That’s because ReSharper looked at the type parameters and realized that Base.Do will be called with T->string (see the second line of results: Base<string>.Dostring means we’re calling a method that substitutes a specific type). Accordingly, ReSharper filtered out Concrete1 because it uses inheritance with the substitution T->int.

Now let’s look at a slightly more complex, yet very vital example using the Visitor pattern. Let’s search for incoming calls from ConcreteVisitor1.VisitNode1 (ReSharper | Inspect | Incoming Calls). Note how we’re going the other way here, in the direction opposite of method calls:


   public interface IVisitor<T>
   {
     void VisitNode1(T data);
   }

   class Node1
   {
     public void Accept<T>(IVisitor<T> v, T data)
     {
       v.VisitNode1(data);
     }
   }

   public class ConcreteVisitor1 : IVisitor<int>
   {
     public void VisitNode1(int data)
     {
     }
   }

   public class ConcreteVisitor2 : IVisitor<string>
   {
     public void VisitNode1(string data)
     {
     }
   }

   public class C1
   {
     void Foo()
     {
       var v = new ConcreteVisitor1();
       new Node1().Accept(v, 1);
     }

     void Foo2()
     {
       var v = new ConcreteVisitor2();
       new Node1().Accept(v, "string");
     }
   }

The result:

Incoming Calls to VisitNode

While traversing the generic Visitor, ReSharper did not lose any details about the substituted type parameters and successfully filtered out the irrelevant call from Foo2. When you have a highly-branched hierarchy and a large number of generic types, this kind of logic helps to really narrow down your search.

Constructors

Let’s also look at an artificial example using constructors and field initializers. Let’s search for outgoing calls from the Derived class constructor:


   class Base
   {
     public Base()
     {
       Base_Bar();
     }

     void Base_Bar()
     {
     }
   }

   class Derived : Base
   {
     int _i = Foo();

     public Derived()
     {
       Bar();
     }

     void Bar()
     {
     }

     static int Foo()
     {
       return 0;
     }
   }

Outgoing Calls From Derived

Again, nothing out of the ordinary. ReSharper simply displays calls in their the natural order, mindfully listing the implicit call of the base constructor. For a less-experienced developer, this saves a lot of time spent understanding code, and is a nice crutch to lean on for an expert.

Value Tracking

And here’s the final tidbit. If you open the ReSharper | Inspect menu, you’ll see two very interesting items: Value Origin and Value Destination. These functions implement value tracking: they let you track where a particular variable value or parameter value came from, or where it is headed. Naturally, it works with collections and delegates (it determines that an item was taken from a collection and then searches for usages of that particular collection) and is indispensable for identifying the causes of NullReferenceExceptions.

Illustrating this will take a whole batch of screenshots and examples, so please stay tuned for our next post.

Author: Alexander Zverev, senior ReSharper developer. Translated from original article (in Russian)

Introducing ReSharper 5.0: Solution-Wide Warnings and Suggestions

Wednesday, January 27th, 2010

Previous posts introducing ReSharper 5.0:

Over the years, ReSharper has gradually advanced from plainly highlighting errors and problems in individual code files to somehow summing up errors and problems in a larger scope, up to the entire solution.

Back in 2007, ReSharper 3.1 was the first product version to introduce Solution-Wide Error Analysis to gather data on all errors in the solution using a single tool window. ReSharper 4.5 split many code inspections to execute in private and public scope, with the latter only available when you turned on Solution-Wide Error Analysis.

Taking another huge step towards instantly seeing every problem anywhere in your solution, ReSharper 5 introduces a new code analysis feature called Solution-Wide Warnings and Suggestions. As you’ve probably guessed, it lists all warnings and suggestions that ReSharper displays in the scope of your whole solution or in a narrower scope, depending on how you call it. In other words, any code smells or other problems that you may have in your solution can now be summarized in a single tool window, making tool-based code review much easier.

When you switch on Solution-Wide Errors Analysis, Solution-Wide Warnings and Suggestions starts showing errors as well, plus warnings and suggestions that work in non-private scope.

That doesn’t mean Errors in Solution tool window becomes obsolete with R# 5: when your goal is as simple as to make your code compile, Errors in Solution quickly indicates that something in the solution went awfully wrong and you should fix things up before you can compile.

However, as soon as you’re ambitious enough to make your code green - that is, eliminate compiler warnings, implement best practices, or upgrade your code to leverage the latest language opportunities - Solution-Wide Warnings and Suggestions is exactly what you need to get the job done quickly.

The feature includes two items:

  • Inspect Code - a new command that is available by right-clicking any node in Solution Explorer, from a single file to the whole solution:
  • Inspection Results - a tool window that actually shows problems found in a certain scope, broken up into several categories:

The Inspection Results tool window is pretty much similar to other ReSharper tool windows like Type Hierarchy or Find Results: it provides common navigation, grouping and export options. It also has a code preview pane where you can instantly see the context of a problem without opening the corresponding file in the text editor:

The tool window is not updated automatically, so as soon as you’ve made substantial changes, make sure to click the Refresh button to see up-to-date inspection results:

In many scenarios, chances are you don’t want to review all code problems you may have in a scope - you’d rather focus on a particular subset. Inspection Results lets you do this by clicking the glaring Filter button:

This displays the Filter Issues dialog box where you can select or unselect individual inspections or even entire inspection groups. For example, here’s how you can discover code that can be transformed to leverage C# 3.0 and C# 4.0 language features:

When you double-click an item in Inspection Results, the corresponding file opens in the text editor in the right position for you to actually take measures: apply a quick-fix, refactor or clean up code, or whatever:

However, instead of double-clicking through all inspections, in many cases you can apply fixes right from Inspection Results: say, you’re inspecting a single file that has three inspection items:

Of the three inspection items, two can be safely fixed using Code Cleanup, which can both delete a redundant “using” directive and make an explicitly typed variable implicitly typed. Then, you press Ctrl+Alt+F right on one of these two inspection items, and the Code Cleanup dialog box displays:

You launch Code Cleanup with Full Cleanup profile, and ReSharper applies fixes for both inspections straight away! Upon refreshing Inspection Results, you only have one inspection left:

In addition to cleaning up code, you can also apply refactorings and navigation actions right from Inspection Results. I hope to cover scenarios involving this approach in subsequent posts about ReSharper 5.

To try out Solution-Wide Warnings and Inspections in its latest incarnation, make sure to download a fresh ReSharper 5 nightly build!

Introducing ReSharper 5.0: Loops 2 LINQ

Friday, December 11th, 2009

On the eve of ReSharper 5.0 going beta, we thought it’s just about time to start elaborating on new R# features. We’re hoping for a series of posts on improved code analysis, navigation to and within external sources, structural search & replace, ASP.NET support, and other stunning capabilities that ReSharper 5.0 provides. Today, we’ll talk about R# going crazy over LINQ.

Among many new code inspections introduced in ReSharper 5.0, two are specifically aimed at converting for and foreach loops into LINQ statements and/or combinations of extension methods and lambda expressions. Here they are:

  • Loop can be converted into LINQ-expression
  • Part of loop’s body can be converted into LINQ-expression

If you are wondering why you would ever transform traditional cozy loops to LINQ, Jimmy Bogard, Matthew Podwysocki, and Justin Etheredge have done a great job of explaining why.

Back to ReSharper work, let’s see how it converts loops to LINQ method or query syntax for you in common scenarios.

First, there’s the aggregation scenario where we loop through a collection in order to get the number of this collection’s items for which a certain condition holds true:

ReSharper highlights the foreach keyword with a green curly underline. You press Alt+Enter for available actions, and ReSharper suggests that you convert the loop to a LINQ expression:

You apply the conversion, and here we go: no more temporary counter variable. Instead, we’ve got Count extension method with a lambda-styled condition:

Next, we’re taking on the transformation scenario where we’re looping though a collection to populate another collection:

Again, ReSharper is smart enough to see that the code fragment can be converted to LINQ method syntax:

On the output side, we’ve got one line of code instead of three, thanks to the ToDictionary extension method:

For the next scenario, let’s take a collection and filter it out, so to speak, like this:

ReSharper encounters three foreach loops and readily suggests that we convert each of them. Because conversion only occurs within a selected loop and its nested loops, let’s press Alt+Enter at the top-level loop:

What we’ve got here is a pretty return statement that leverages LINQ query syntax:

All three examples above show how ReSharper converts entire loops to LINQ. In many cases, specifically with write usages inside loops, that can’t be done. For such occasions, ReSharper provides its second LINQ-related inspection: Part of loop’s body can be converted into LINQ-expression. Unlike the previous action, it’s displayed as a hint and highlighted with a straight green underline.

Let’s take another foreach loop with a complex condition and a write usage inside:

Pressing Alt+Enter at the foreach keyword highlighted as a hint lets you convert a part of the loop to LINQ syntax:

ReSharper integrates the condition with iteration variable definition, resulting in a LINQ query that makes the previously bloated write usage clear:

If, for any reason, you want to keep your loops for future generations and you don’t need LINQ-related code inspections, or, say, you want them to display as warnings or even errors, you can always configure them by choosing ReSharper | Options | Code Inspection | Severity.

The two loop 2 LINQ inspections and many more exciting features are available right now: we keep publishing fresh ReSharper 5 nightly builds that you can download and evaluate.

ReSharper in Detail: Navigate from Here

Tuesday, November 11th, 2008

A subset of ReSharper’s navigation features is designed to help you promptly navigate from one symbol to another. These features are:
 

  • Go to Declaration
  • Go to Type Declaration
  • Go to Base
  • Go to Inheritor
  • Go to Usage

 
Two common ways to call them are to choose corresponding menu items or hit keyboard shortcuts, but there’s a third, by far the most convenient way, which is to invoke the Navigate from Here drop-down list upon the current symbol in the text editor (or upon a selected entry in File Structure or another ReSharper tool window) by pressing Ctrl+Shift+G:
 

 
Not only does this drop-down list provide a handy multiple-choice navigation technique, but it also extends a developer’s toolset with a bunch of “secret” navigation features that are not available from the ReSharper menu.

Control Flow Target

(Works in text editor only)
Function: navigates to next control flow recipient.
Available for: foreach, yield, jump statements (break, continue, goto, return), throw statement.
For example, in the following code fragment, selecting Control Flow Target upon the continue statement brings the caret to the next iteration of the enclosing iteration statement, i.e. –i:
 

Function Exit(s)

(Works in text editor only)
Function: navigates to member exit point or highlights alternative exit points.
Available for: getters and setters in properties, constructor names, return statement (alternative exit points are highlighted, if any), throw statement.
For example, invoking Go to Function Exit(s) upon the name of the following constructor highlights throw statements in if clauses, as well as the closing constructor body delimiter:
 

Implementing Members

Function: highlights interface members implemented in the current class.
Available for: base interface entries in implementing class declaration:
 

Overriding Members

Function: highlights abstract class members overridden in the current class.
Available for: base class entries in inheriting class declaration.
Works similar to Implementing Members

Conflicting Declaration(s)

Function: navigates to a member with identical signature in the current scope.
Available for: any of conflicting member declarations:
 

Member Overloads

Function: navigates to an overloading member or (if there are two or more of them) highlights such members in the text editor.
Available: anywhere within overloadable members:
 

To-do Explorer

Function: navigates from a to-do item in the text editor to its corresponding entry in the To-Do Explorer.
Available for: to-do items:
 

Test Explorer

Function: navigates from a unit test or test class in the text editor to its corresponding node in the Unit Test Explorer.
Available anywhere within test classes, unit tests:
 

 
As a finishing note, remember that whenever you execute a “Navigate from Here” action that highlights a set of symbols that are not entirely visible on the current screen, you can navigate to the highlights using ReSharper Marker Bar (take a note of blue markers in the example for Member Overloads). When you’ve finished examining the highlights, press Esc to remove them.