microsoft / CodeContracts

Source code for the CodeContracts tools for .NET
Other
882 stars 150 forks source link

Use nameof in VS2015 code snippets #199

Open fedotovalex opened 9 years ago

fedotovalex commented 9 years ago

Currently precondition snippets include the name of the parameter as a string literal, e.g.

cren => Conract.Requires<ArgumentNullException>(arg != null, "arg");

For Visual Studio 2015, it makes sense to use nameof() instead of a string literal, e.g.

cren => Conract.Requires<ArgumentNullException>(arg != null, nameof(arg));

normanhh3 commented 7 years ago

I am running into an error: " error CC1065: User message to contract call can only be string literal, or a static field, or static property that is at least internally visible." because of the use of $"{nameof(parameterName)} something went wrong" in my code. For now, I'll switch those to magic strings, but it really makes sense to not trigger on the use of nameof if possible.

yaakov-h commented 7 years ago

Use nameof(arg), which gets compiled as a string literal, not $"{something}", which gets compiled as a call to string.Format.

normanhh3 commented 7 years ago

Are you thinking something like:

nameof(param) + " is required!"

yaakov-h commented 7 years ago

Interestingly - at least with Roslyn 2.0 (VS2017) - the following each get compiled as a single constant string:

nameof(Foo)
"A" + nameof(Foo)
nameof(Foo) + "A"
"A" + nameof(Foo) + "A"

whereas the following do not:

$"{nameof(Foo)}"
$"A{nameof(Foo)}A"
normanhh3 commented 7 years ago

@yaakov-h the discrepancy you identify is precisely what my comment was referring to.