One of the strengths of Rider is code analysis. Rider comes with over 2400 code inspections that analyze our code at design time, allowing us to instantly see any errors, problems or potential improvements – whether in the current file or in our entire solution.
In this blog series, we’ll look at what code analysis is, how it can do automated code review and how it helps us improve the quality of our code. Once we covered that, we’ll look into some of the inspection categories that are available and how they can help spot and resolve potential issues in our codebase.
In this series: (table of contents will be updated as we progress)
Let’s start at the beginning: what is code analysis?
What is code analysis?
How do we know if our code is correct? Unfortunately, there is no single answer to that question. We have to rely on various methods to validate code correctness:
- Compile our code to check for compilation errors.
- Run our application to check for issues at runtime.
- Write and run unit tests to validate code logic.
There’s a downside to these three ways of validating code: they all require an explicit action. For example, to detect runtime errors we have to run our application, click through it and see if things are okay. We have to attach a profiler to figure out whether we implemented the Disposable pattern correctly. What if we could detect potential issues while writing code?
Code Analysis continuously looks at what we are doing and tries to determine what we want to achieve. Rider looks at individual statements and at our overall solution architecture. If it detects a potential issue, it will show a warning. It may show suggestions too, helping us make our code better. Let’s look at an example.
What does it look like in the editor?
We can access code analysis in a number of places, but let’s start with a place where it’s very obvious: in the editor. We’ll see our code get underlined with a “squiggle”, its color based on the severity of the code inspection result (hint, suggestion, warning, error).
Hovering over an inspection shows us what the issue is. In this case, we’re casting a
Person to a
Customer, which could result in a
NullReferenceException at runtime.