How to Use Roslynator to Destroy Unhealthy Code


People often don’t realize how bad their code is until they receive a bug report or get hit with a performance issue.

However, sometimes bad code can mean the code that isn’t used anywhere in the app. Luckily, you can use Roslynator to find and eliminate this code.

Roslynator is a set of 500+ analyzers and 200+ refactorings for C#, powered by the Roslyn compiler. You can use it through the command-line interface or install it on Visual Studio 2022 and VS Code.

If you’re looking for a way to have clean code, Roslynator is the perfect tool for the job. Its powerful static code analysis capabilities can help you find and fix problems in your code, making it more robust.

What is Roslynator?

When creating a bug-free software program, you need to understand how to create quality code. You cannot just throw out all the code that has code smells and expect to get a quality product. Sooner or later, you will have to spend hours and hours trying to fix every bug that your application has.

Creating a quality program that won’t have bugs can be a huge hassle. But luckily, you can install and use Roslynator to help you create high-quality code.

Roslynator is a set of analyzers, code fixes, and refactorings for the C# programming language.

It was created by Josef Pihrt. Roslynator offers over 500 analyzers and code fixes and over 200 refactorings. Roslynator is available as open-source on GitHub.

Roslynator is a handy tool for C# developers. It can help you find and fix errors in your code and can also be used to improve your code quality. It is an invaluable tool for anyone looking to improve their C# code and development skills.

Another way to improve your C# code and development skills is to read the article about clean code. It has 31 tips to clean every C# code.

Roslynator is based on Roslyn, Microsoft’s C# compiler platform.

How to install Roslynator?

You can use Roslynator through the command-line interface or install it on Visual Studio 2022 or Visual Studio code.

To install Roslynator on Visual Studio 2022, download it from the Visual Studio Marketplace.

To install Roslynator on Visual Studio Code, download it from the Visual Studio Code Marketplace.

Visual Studio Code Marketplace

You can also install it through NuGet. Type the following command in your NuGet package manager:

Install-Package Roslynator.Analyzers

You can also use Roslynator to implement your analyzers and refactorings. To do that, install the following NuGet package:

Install-Package Roslynator.Core

What is Roslyn?

Roslyn is a set of open-source compilers and code analysis APIs for C# and Visual Basic (VB.NET) languages from Microsoft. It has tools to programmatically assess, edit, and compile C# and VB.NET code.

In addition, it provides language services that extend languages, supporting features such as IntelliSense, code navigation, syntax coloring, code analysis, and code refactoring.

Roslyn provides a set of APIs to manipulate C# and VB.NET code, allowing developers to write code analysis tools and refactoring tools on top of them. In addition, its open-source nature enables developers to freely contribute to the project, create new tools, and extend the compilers and editors to support additional functionality.

Rosyln contains three layers:

  • Language Service
  • Compiler API
  • Compiler Pipeline
roslyn compiler

What is the difference between analyzer and refactorings?

At the beginning of the article, I mentioned that Roslynator offers analyzers and refactorings to improve the code. Even though these two terms sound similar, there are some differences.

Analyzers can identify issues in the syntax or structure of your code. Then Roslynator uses code fixes to offer a recommended solution based on these errors. It continuously runs in the background of your Visual Studio instance and checks the code. Then it offers you the most appropriate tools available for making quick fixes whenever they’re necessary.

There are two ways of code checking. The first one is a static analysis, and the second one is dynamic analysis. Analyzers use static analysis to check the code. Static analysis involves scanning your program without running it. For example, it can help determine any bugs within your code by inspecting its syntax and structure. On the other hand, dynamic analysis involves executing a program by loading its binary form into memory and examining its behavior as it runs.

The other part of the Roslyn is code refactorings. Code refactorings offer on-demand operation for a given code block. They don’t run continuously in the background. Instead, you call them when you want to perform a specific refactoring.

The best example is using the Extract Method refactoring to create a new method and place an existing code block in it.

Check out the following article for more information on using the Extract Method refactoring to improve your code.

How to use Roslynator to improve code

You have probably seen code that you could write in a much simpler way. But sometimes, you miss the opportunity to improve the code right on the spot instantly. So how to make sure you write clean code? Roslynator is a tool that makes coding easier.

The top most useful Roslynator analyzers

Roslynator offers plenty of analyzers that can improve your code. You can see the comprehensive list here. In this section, let’s go through some analyzers that can make the most difference to your code.

Simplify nested using statement

Before:

using (var fs = new FileStream("path", FileMode.OpenOrCreate))
{
    using (var sr = new StreamReader(fs))
    {
    }
}

After:

using (var fs = new FileStream("path", FileMode.OpenOrCreate))
using (var sr = new StreamReader(fs))
{
}

Here is how it looks like inside Visual Studio:

Merge ‘else’ with nested ‘if’

Before:

if (condition1)
{
    Method1();
}
else
{
    if (condition2)
    {
        Method2();
    }
}

After:

if (condition1)
{
    Method1();
}
else if (condition2)
{
    Method2();
}

Merge ‘if’ with nested ‘if’

Before:

if (condition1)
{
    if (condition2)
    {
    }
}

After:

if (condition1 && condition2)
{
}

Other particularly useful analyzers are:

  1. Convert ‘if’ to ‘return’ statement
  2. Inline local variable
  3. Make field read-only
  4. Use method chaining
  5. Avoid NullReferenceException
  6. Use conditional access instead of conditional expression
  7. Avoid nested ?: operators

These are some of the analyzers worth checking, but there are a lot more that can be useful in your development.

The top most useful Roslynator refactorings

When it comes to refactoring support inside Visual Studio, it has improved immensely over the last few years. However, sometimes you need extra refactoring tools to improve your code further. Let’s see top Roslynator refactorings.

Add member to interface

Before:

public class Customer : ICustomer
{
    public void GetOrders()
    {
    }
}

public interface ICustomer
{
}

After:

public class Customer : ICustomer
{
    public void GetOrders()
    {
    }
}

public interface ICustomer
{
    void GetOrders();
}

Add missing cases to switch statement

Before:

switch (dayOfWeek)
{
    case DayOfWeek.Monday:
        break;
    case DayOfWeek.Tuesday:
        break;
    case DayOfWeek.Wednesday:
        break;
    case DayOfWeek.Thursday:
        break;
}

After:

switch (dayOfWeek)
{
    case DayOfWeek.Monday:
        break;
    case DayOfWeek.Tuesday:
        break;
    case DayOfWeek.Wednesday:
        break;
    case DayOfWeek.Thursday:
        break;
    case DayOfWeek.Friday:
        break;
    case DayOfWeek.Saturday:
        break;
    case DayOfWeek.Sunday:
        break;
}

Initialize field from constructor

Before:

public class Customer
{
    private string _name;

    public Customer()
    {
    }

    public Customer(object parameter)
    {
    }
}

After:

public class Customer
{
    private string _name;

    public Foo(string name)
    {
        _name = name;
    }

    public Foo(object parameter, string name)
    {
        _name = name;
    }
}

Other refactorings that can be particularly useful:

  1. Convert ‘string.Format’ to interpolated string
  2. Generate base constructors
  3. Insert string interpolation
  4. Introduce constructor
  5. Introduce local variable
  6. Invert if
  7. Merge ‘if’ statements
  8. Merge if with parent if
  9. Rename method according to type name
  10. Wrap lines in try-catch

All in all, Roslynator is a good extension that offers a wide range of refactoring support.

Roslynator vs Resharper

Resharper is a commercial code analysis tool that allows you to inspect your .NET and C++ code. It is a powerful productivity tool for developers. It includes code refactoring, error highlighting, IntelliSense, smart code navigation, and code formatting tools.

All in all, Resharper is a powerful IDE for .NET developers that help you manage your projects and build and debug code faster than ever before.

However, there are two significant downsides of the Resharper:

  1. Performance hit – you need a powerful machine to run Visual Studio with installed Resharper. Otherwise, it can take a bit longer to open a Visual Studio and initially load the project.
  2. Price – Resharper is not free. Even though you could argue that the productivity boost you gain is worth the money spent, a single Reshaper license costs $129 for the first year. But you need to renew the license every year.

Many developers consider using Roslynator as a replacement for Resharper. What are the pros and cons? Roslynator offers a similar set of analyzers and refactoring tools. It is free and open-sourced. Also, you can extend it.

On the other side, Resharper offers advanced solution-wide refactoring featurescompliance with team coding standards, and its unit test runner. But to fully utilize Resharper, you must take the time and learn all its powerful features.

In summary, if you have the money and are ready to learn Resharper in and out, use Resharper. On the other hand, if you want quick refactoring help here and there, and are ready to perform more complex refactorings manually, then Roslynator is all you need.

If you are looking for another Resharper alternative, here are five free Resharper alternatives that offer great features.

Conclusion

We live in a world where the speed of software development has become a critical factor in the success of any company. To stay competitive, you must ensure that your code is as fast and bug-free as possible.

Roslynator is a set of tools that help you to do that. It offers you a set of 500+ analyzers and 200+ refactorings for C#, which you can use to detect and correct a wide range of errors and bad practices in your code.

Roslynator is a free, open-source code analysis tool. So try it today and start improving your code.

Recent Posts