A publicly accessible method can be called from anywhere, which means you should validate parameters to be within the expected constraints. In general, checking against ``++null++`` is recommended defensive programming.
This rule raises an issue when a parameter of a publicly accessible method is not validated against ``++null++`` before being dereferenced.
== Noncompliant Code Example
----
public class MyClass
{
private MyOtherClass other;
public void Foo(MyOtherClass other)
{
this.other = other; // Compliant: other not being dereferenced
}
public void Bar(MyOtherClass other)
{
this.other = other.Clone(); // Noncompliant
}
protected void FooBar(MyOtherClass other)
{
this.other = other.Clone(); // Noncompliant
}
}
----
== Compliant Solution
----
public class MyClass
{
private MyOtherClass other;
public void Foo(MyOtherClass other)
{
this.other = other;
}
public void Bar(MyOtherClass other)
{
if (other != null)
{
this.other = other.Clone();
}
}
protected void FooBar(MyOtherClass other)
{
if (other != null)
{
this.other = other.Clone();
}
}
}
----
== Exceptions
To create a custom null validation method declare an attribute with name ``++ValidatedNotNullAttribute++`` and mark the parameter that is validated for null in your method declaration with it:
----
using System;
public sealed class ValidatedNotNullAttribute : Attribute { }
public static class Guard
{
public static void NotNull<T>([ValidatedNotNullAttribute] this T value, string name) where T : class