CA2243: Attribute string literals should parse correctly

TypeName

AttributeStringLiteralsShouldParseCorrectly

CheckId

CA2243

Category

Microsoft.Usage

Breaking Change

Non Breaking

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 System.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 Suppress Warnings

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

Example

The following example shows code for the AssemblyFileVersionAttribute that violates this rule.

using System;
using System.Runtime.InteropServices;

namespace Samples
{
    [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
    [ComVisible(true)]
    public sealed class AssemblyFileVersionAttribute : Attribute
    {
        public AssemblyFileVersionAttribute(string version) { }

        public string Version { get; set; }
    }

    // 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 following code: [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

CA1054: URI parameters should not be strings