10

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964

5 Answers5

10

Like this?

public MyClass(SomeOtherClass source) : this(source, source == null ? null : source.Name) { }
public MyClass(SomeOtherClass source, string name) { /* ... */ }
arbiter
  • 9,447
  • 1
  • 32
  • 43
  • Yes, that's it. You can use any static method also. – vgru Jun 29 '09 at 18:28
  • Unfortunately this is rather unwieldy when a single parameter constructor uses its parameter value's properties to pass values as arguments for another constructor with many parameters (e.g. converting JavaScript-style "parameter object" to scalar parameters). I wish C# allowed for `static`-scoped code to run before a superclass' constructor so complex validation logic can be applied. – Dai May 10 '19 at 20:38
1

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.

Jeff Yates
  • 61,417
  • 20
  • 137
  • 189
1

Since this question was asked some time ago I just want to note with the later features in C# you can now also use this:

public MyClass(SomeOtherClass source) : this(source, source?.Name) { }
Cornelius
  • 3,526
  • 7
  • 37
  • 49
1

Since C# 7.0 you can also do this:

public MyClass(SomeOtherClass source) : this(source?.Name ?? throw new ArgumentNullException(nameof(source))) { }

C# 7.0 allows throwing exceptions as expressions. (See Microsoft Docs)

JackDMF
  • 70
  • 8
0

I would say the only way to fix this warning would be to turn it off. FxCop is a great tool but sometimes you need to remember that it is just a tool and can make suggestions that are not always fitting to your code.

In this example I would say ignore the warning or disable it if you don't want to see it.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635