V3148. Casting potential 'null' value to a value type can lead to NullReferenceException.

The analyzer has detected an unsafe cast of a potentially null reference to a value type. Even though no dereference as such takes place in this case, such a cast will still result in raising a 'NullReferenceException'. The simplest way to get this behavior is as follows:

void Foo()
{
  object b = null;
  var c = (bool)b;
}

This is what the fixed code should look like:

void Foo()
{
  object b = null;
  var c = (bool)(b ?? false);
}

A warning will also be issued if a potentially null variable is found to be cast to any value type, say, struct:

protected override void ProcessMessageAfterSend(....)
{
  ....
  (DateTime)msg.GetMetadata(....);
  ....
}
public object GetMetadata(string tag)
{
  object data;
  if (metadata != null && metadata.TryGetValue(tag, out data))
  { return data; }
  return null;
}

The diagnostic checked the return result of the 'GetMetadata' method and found that it could return 'null'. The type cast in this example needs a null check too:

protected override void ProcessMessageAfterSend(....)
{
  ....
  (DateTime)(msg.GetMetadata(....) ?? new DateTime());
  ....
}

According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-476.

You can look at examples of errors detected by the V3148 diagnostic.


Bugs Found

Checked Projects
409
Collected Errors
14 072
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →
Accept