Attribute string literals should parse correctly

This warning is supported in the stand-alone version of FxCop only. It is not supported in Code Analysis, which is integrated into Visual Studio.

TypeName

AttributeStringLiteralsShouldParseCorrectly

CheckId

CA2243

Category

Microsoft.Usage

Breaking Change

NonBreaking

Cause

An attribute's string literal parameter does not parse correctly for a URL, GUID, or Version.

Rule Description

Since attributes are derived from System.Attribute, and attributes are used at compile time, only constant values can be passed to their constructors. Attribute parameters that must represent URLs, GUIDs and Versions cannot be typed as Sytem.Uri, System.Guid, and System.Version, because these types cannot be represented as constants. Instead, they must be represented by strings.

Because the parameter is typed as a string, it is possible that an incorrectly formatted parameter could be passed at compile time.

This rule uses a naming heuristic to find parameters that represent a uniform resource identifier (URI), a Globally Unique Identifier (GUID) or a Version and verifies that the passed value is correct.

How to Fix Violations

Change the parameter string to a correctly formed URL, GUID, or Version.

When to Exclude Warnings

It is safe to exclude a warning from this rule if the parameter does not represent a URL, GUID, or Version.

Example

The following example shows an attribute for a System.AssemblyFileVersionAttribute that violates this rule.

    [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
    [ComVisible(true)]
    public sealed class AssemblyFileVersionAttribute : Attribute
    {
        public AssemblyFileVersionAttribute(string version);
 
        public string Version { get; }
    }
// Since the parameter is typed as a string, it is possible
// to pass an invalid version number at compile time. The rule
// would be violated by the code below:
[assembly: AssemblyFileVersion("xxxxx")]

The rule is triggered by the following:

  • Parameters that contain ‘version’ and cannot be parsed to System.Version.

  • Parameters that contain ‘guid’ and cannot be parsed to System.Guid.

  • Parameters that contain ‘uri’, 'urn', or ‘url’ and cannot be parsed to System.Uri.

See Also

Reference

Uri parameters should not be strings