Always check the result of an as operation (AV1570)If you use 'as' to obtain a certain interface reference from an object, always ensure that this operation does not return null. Failure to do so may cause a NullReferenceException at a much later stage if the object did not implement that interface.
New language features to consider:
is-patterns
Testing for interface implementation using as nowadays triggers a Resharper refactoring suggestion to replace the expression with an is-pattern. Example:
interface IUser { }
class RemoteUser : IUser { }
class Example
{
void Test(IUser user)
{
var remoteUser = user as RemoteUser;
// ~~~~~~ Resharper: Use pattern matching
if (remoteUser != null)
{
// ...
}
}
}
which is then changed to:
```csharp
if (user is RemoteUser remoteUser)
I think we should remove this rule, because it advocates outdated language usage.
Aside from that, the description is incorrect: "If you use 'as' to obtain a certain interface reference from an object..." should be reversed. An object either implements the interface, which makes the test redundant -or- the compiler issues an error because no conversion exists. The text should be: "If you use 'as' to safely upcast an interface reference to a certain object..."
Existing rule:
Always check the result of an as operation (AV1570)
If you use 'as' to obtain a certain interface reference from an object, always ensure that this operation does not return null. Failure to do so may cause a NullReferenceException at a much later stage if the object did not implement that interface.
New language features to consider:
as
nowadays triggers a Resharper refactoring suggestion to replace the expression with an is-pattern. Example:class RemoteUser : IUser { }
class Example { void Test(IUser user) { var remoteUser = user as RemoteUser; //
~~~~~~ Resharper: Use pattern matching}
I think we should remove this rule, because it advocates outdated language usage.
Aside from that, the description is incorrect: "If you use 'as' to obtain a certain interface reference from an object..." should be reversed. An object either implements the interface, which makes the test redundant -or- the compiler issues an error because no conversion exists. The text should be: "If you use 'as' to safely upcast an interface reference to a certain object..."