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:
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);
This diagnostic is classified as:
You can look at examples of errors detected by the V3051 diagnostic. |