CA2243: Attribute string literals should parse correctly

Property Value
Rule ID CA2243
Title Attribute string literals should parse correctly
Category Usage
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 No

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.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA2243
// The code that's violating the rule is on this line.
#pragma warning restore CA2243

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA2243.severity = none

For more information, see How to suppress code analysis warnings.

Example

The following example shows code for the 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; 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:

  • 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