V3168. Awaiting on expression with potential null value can lead to throwing of 'NullReferenceException'.
The analyzer detected a suspicious fragment: the 'await' operator is used with an expression whose value can be a null reference. When using 'await' with 'null', an exception of the 'NullReferenceException' type will be thrown.
Consider an example:
async void Broadcast(....)
{
await waiter.GetExplorerBehavior()?.SaveMatches();
....
}
ExplorerBehavior GetExplorerBehavior()
{
return _state == NodeState.HandShaked ? _Node.Behavior : null;
}
In the 'Broadcast' method, the 'await' operator is used with an expression that may have the 'null' value in certain cases. The 'GetExplorerBehaviour' method returns 'null' under some circumstances. 'null' might later get into 'Broadcast'.
As a result, when using the 'await' operator with a 'null' expression we'll get 'NullReferenceException'.
As a fix, one can add an additional 'null' check to the 'Broadcast' method:
async void Broadcast(....)
{
var task = waiter.GetExplorerBehavior()?.SaveMatches();
if (task != null)
await task;
....
}
The analyzer also warns about cases when a potentially null reference is passed to a method, constructor, or property, within which it can be used with 'await'. Example:
void ExecuteActionAsync(Action action)
{
Task task = null;
if (action != null)
task = new Task(action);
ExecuteTask(task); // <=
....
}
async void ExecuteTask(Task task)
{
....
await task;
}
In this fragment, 'await' is used with the 'task' parameter. A potentially null reference is passed to the parameter. Here is a fixed code fragment of the 'ExecuteActionAsync' method:
void ExecuteActionAsync(Action action)
{
Task task = null;
if (action != null)
{
task = new Task(action);
ExecuteTask(task);
}
....
}
This diagnostic is classified as:
You can look at examples of errors detected by the V3168 diagnostic. |