C# Analyzer: 30+ new static analysis checks

If you use DeepSource for your C# projects, here’s some excellent news: in the latest release of DeepSource Cloud and Enterprise Server, we’ve added 32 new checks in our C# Analyzer for detecting more performance issues, bug risks and antipatterns.

Here’s a preview of some of the notable checks. Scroll down to the bottom of this post to see the complete list of all new checks!

(CS-P1016) Use ContainsKey() to check if a key exists in a Dictionary<T, K>

If you wish to check if a key exists in a Dictionary, consider using the ContainsKey() that ideally has a complexity of O(1). Using the .Keys.Contains() deteriorates the performance as it has a complexity of O(n) where n = number of elements in your Dictionary.

Bad practice:

if (dict.Keys.Contains(key))
{
    // ...
}

Recommended:

if (dict.ContainsKey(key))
{
    // ...
}

(CS-W1044) Lock is obtained on an entity that does not guarantee reliable mutual exclusion

Microsoft guidelines specifically state that lock's should not be obtained on this, System. Type’s, and string instances. Doing so may cause deadlock or lock contention, thereby affecting your application’s execution and reliability. It is generally recommended that you dedicate a private readonly object solely for locking.

Bad practice:

lock(this)
{
    // ...
}

Recommended:

// _lockObj is an `object` that is class' private read-only member.
lock(_lockObj)
{
    // ...
}

(CS-W1047) An async method should have at least a single awaitable

A method with an async modifier indicates that it involves asynchronous work. Not having any await expressions inside the method makes the async modifier redundant, and the method proceeds synchronously. Consider adding appropriate await expressions or dropping the async modifier.


Explore all new static analysis checks:

1 Like