Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating C# base class constructor parameter

After running Code Analysis in VS2010 beta (FxCop for previous versions) I'm getting the following warning:

In externally visible method 'Identity.Identity(WindowsIdentity)', validate parameter 'windowsIdentity' before using it.

The constructor is:

public Identity(WindowsIdentity windowsIdentity)
         : base(windowsIdentity.Token)
{
         init();
}

for a class defined as:

public class Identity : WindowsIdentity

My question is, how do I validate the windowsIdentity parameter? Should I validate it in the constructor, and throw an exception, or is there a better way to call this?

like image 964
Steve Avatar asked Dec 17 '09 19:12

Steve


3 Answers

As of C# 6.0 you can use null-coalescing operator combined with the null-conditional operator like this:

public Identity(WindowsIdentity winIdentity)
    : base(winIdentity?.Token ?? throw new ArgumentNullException(nameof(winIdentity)))
{
    init();
}
like image 188
Jogge Avatar answered Oct 22 '22 02:10

Jogge


You can validate it in a static method:

public Identity(WindowsIdentity windowsIdentity)
         : base(GetToken(windowsIdentity))
{
         init();
}

static Token GetToken(WindowsIdentity ident)
{
    if(ident == null)
        throw new ArgumentNullException("ident");

    return ident.Token;
}

(I didn't bother to look for the type of WindowsIdentity.Token, but you get the idea)

like image 43
Sander Rijken Avatar answered Oct 22 '22 01:10

Sander Rijken


I believe FXCop reports this error here because it thinks that you could encounter a NullReferenceException by accessing windowsIdentity when calling the base class constructor.

One way to add a validation check for null would be to add a static private function to your class that that can check the WindowsIdentity parameter for null and take appropriate action:

private static WindowsIdentity ValidateIdentity( WindowsIdentity identity )
{
    if( identity == null )
        throw new ArgumentNullException( "identity" );
    // possibly some other validation checks here...

    return identity;        
}

public Identity(WindowsIdentity windowsIdentity)
    : base( ValidateIdentity( windowsIdentity ).Token )
{
     init();
}

Another approach would be to use the ternary operator to verify the parameter, as in:

public Identity(WindowsIdentity windowsIdentity)
    : base( windowsIdentity == null ? null : windowsIdentity.Token )
{
     init();
}

But, what you should really ask yourself is what would you do? If you're simply going to throw an exception, it may be ok to let the code stand as is, since it will already through a NullReferenceException if the argument is null.

like image 38
LBushkin Avatar answered Oct 22 '22 01:10

LBushkin