V3051. An excessive type cast or check. The object is already of the same type.


An expression with a redundant operator 'as' or 'is' was detected. It makes no sense casting an object to or checking its compatibility with its own type. Such operations are usually just redundant code, but sometimes they may indicate a bug. To figure out what this bug pattern is about, let's discuss a few examples.

A synthetic example:

public void SomeMethod(String str)
{
  var localStr = str as String;
  ....
}

When initializing the 'localStr' variable, object 'str' is explicitly cast to type 'String', although it's not necessary since 'str' is already of type 'String'.

The fixed version would then look like this:

public void SomeMethod(String str)
{
  String localStr = str;
  ....
}

Instead of explicitly specifying the 'localStr' object type, the programmer could have kept the keyword 'var' here, but explicit type specification makes the program clearer.

The following is a more interesting example:

public object FindName(string name, FrameworkElement templatedParent);
....
lineArrow = (Grid)Template.FindName("lineArrow", this) as Grid;
if (lineArrow != null);
....

Let's examine the line with casts closer to see what's happening:

  • Method 'FindName' returns an object of type 'object', which the programmer tries to explicitly cast to type 'Grid'.
  • If this cast fails, an 'InvalidCastException' will be raised.
  • If, on the contrary, the cast is successful, the object will be again cast to the same type, 'Grid', using the 'as' operator. Then the cast is guaranteed to be successful, and this cast is redundant.
  • As a result, if the cast fails, 'lineArrow' will never be assigned the value 'null'.

As suggested by the next line, it is assumed that 'lineArrow' may refer to the 'null' value, so it is exactly the 'as' operator that is supposed to be used. As explained before, 'lineArrow' can't take the value 'null' if the cast fails. Therefore, it's not just a redundant cast – it's an apparent error.

To solve this issue, we can remove the extra cast operation from the code:

lineArrow = Template.FindName("lineArrow", this) as Grid;
if (lineArrow != null);

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

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


Bugs Found

Checked Projects
344
Collected Errors
12 970