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?
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();
}
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With