Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CA1062: ValidateArgumentsOfPublicMethods on co-constructor calls

I have a class with two constructors that look like this:

public MyClass(SomeOtherClass source) : this(source, source.Name) { }
public MyClass(SomeOtherClass source, string name) { /* ... */ }

When I run FxCop, it correctly reports a violation of CA1062: ValidateArgumentsOfPublicMethods, because if source is null in the first constructor, it will throw a NullReferenceException on source.Name.

Is there any way to fix this warning?

I could make an extension method that checks for null and returns its argument, but it would be ugly. Also, as I understand, it wouldn't resolve the warning because FxCop wouldn't realize what it does.

like image 320
SLaks Avatar asked Jun 29 '09 18:06

SLaks


2 Answers

Like this?

public MyClass(SomeOtherClass source) : this(source, source == null ? null : source.Name) { }
public MyClass(SomeOtherClass source, string name) { /* ... */ }
like image 168
arbiter Avatar answered Sep 24 '22 02:09

arbiter


There are legitimate times to turn off FxCop warnings and this could very well be one, but you can correct the problem by either a ternary expression that checks for null and throws an exception (or substitutes a default value), or a call to a static method that checks for null and throws the appropriate exception.

like image 20
Jeff Yates Avatar answered Sep 22 '22 02:09

Jeff Yates