CA2204 warning for mentioning type name in string literal
c#, code-analysis, visual-studio
Solution
With Visual Studio 2017 †, I have demonstrated that Code Analysis warning CA2204: Literals should be spelled correctly can be avoided by using the following additions to C# version 6:
- $ - string interpolation, and
- nameof operator.
if (atr == null)
{
throw new InvalidOperationException(
$"No {nameof(ContentProperty)} attribute found on type.");
}
You may also find my answer to String Interpolation in Visual Studio 2015 and IFormatProvider (CA1305) for avoiding CA1305: Specify IFormatProvider to be helpful.
† Note that C# version 6 was delivered with Visual Studio 2013. A newer version of Visual Studio (with a newer version of Code Analysis) might also be necessary to avoid this warning.
Problem
Consider the following C# code: ``` if (atr == null) throw new InvalidOperationException("No ContentProperty attribute found on type."); ``` When building the project, a "`CA2204`: Literals should be spelled correctly" warning is issued because of unrecognized word "ContentProperty". I am aware that I could disable the rule (either globally or for the containing method only) or create a custom Code Analysis dictionary and add "ContentProperty" in it as a recognized word. However, none of these solutions sounds appealing to me. Referring to a type or class member name in an exception message is bound to happen quite a lot in my project, which is an application framework. Does Code Analysis has a way to tell that a word / group of words isn't meant to be spell-checked, like when surrounded by quotation marks or something? Or is disabling the warning the only way around this?