GurdeepS
GurdeepS

Reputation: 67223

Can't write string in exception constructor

Visual Studio seems to complain when I pass a string into an exception parameter.

if (str1 == null || str2 == null)
{
    throw new ArgumentNullException("lmkl");
}

Visual Studio says that it cannot resolve symbol "lmkl".

If I have a string variable (eg above throw new... string s = "test";) and include this as the parameter for the exception, Visual Studio is more than happy with this.

What gives?

Thanks

Upvotes: 2

Views: 939

Answers (3)

Greg R Taylor
Greg R Taylor

Reputation: 3676

If you're using ReSharper, this should suppress the warning (assuming str1 is the name of your param):

throw new ArgumentNullException(nameof(str1));

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062945

Actually, Visual Studio doesn't care about this at all. I assume you have ReSharper installed? This validates a lot of common errors, including incorrect use of patterns such as ArgumentException etc. It also has better null checking - not quite "contracts", but still pretty helpful.

It only attempts this when it can see a string literal used in a known pattern - the analysis to chase how you assign variables is simply too much for realistic analysis.

Upvotes: 7

Richard Ev
Richard Ev

Reputation: 54117

The documentation for the overloaded constructor for ArgumentNullException that takes a single string parameter states that this argument should be:

The name of the parameter that caused the exception.

At the moment, if your code throws an exception you won't know which argument was null.

Recommend rewriting to

if (str1 == null) throw new ArgumentNullException("str1");
if (str2 == null) throw new ArgumentNullException("str2"); 

Upvotes: 7

Related Questions