Why is SonarQube complaining in this code? I read explanation, but din't really understand why and what I need to do, to make it go away.
Link to SonarQube Rule
public async Task Add(SomeModel obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
var obj2 = new OtherObject();
obj2.UpdateWith(obj);
await _localDatabaseService.AddAsync(obj2);
}
Changing code to look like this does not resolve issue.
public Task Add(SomeModel obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
return AddInternal(obj);
}
private async Task AddInternal(SomeModel obj)
{
var obj2 = new OtherObject();
obj2.UpdateWith(obj);
await _localDatabaseService.AddAsync(i);
}
I just tried your examples and the issue isn't raised on your second code (replacing AddAsync(i)
with AddAsync(obj2)
to match first code logic.
Regarding the explanation of the rule I think the website is pretty clear but let me provide a code sample to try and illustrate the wrong behavior.
static async void Main(string[] args)
{
var x = new Program().Add(null); // Exception is not raised here...
// do some other things
await x; // ... but here when awaited
}
As you can see the issue isn't raised when you expect it.
Obviously, if you are sure that you NEVER end up in this kind of situation and that no-one would use your method in this way you can turn-off the rule.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With