Skip to content

Difference between enum AttributeTargets type in C# and CLI specs #1376

@RexJaeschke

Description

@RexJaeschke

We might well close this without action, but as it took me a while to figure out what was going on here, I thought I'd leave a trail for future inquiring minds.

C.2 of the C# spec has the following:

public enum AttributeTargets

while the CLI spec for this type says it also has the attribute FlagsAttribute. And while this attribute is part of the CLI library, it is not declared in C.2, which raises the question, "If we "inherit" the CLI definition for type AttributeTargets but don't add the attribute, are we obliged to say so?"

The one case in which I can find that this matters is with ToString of an instance of an enum type. (See example below, taken directly from the CLI library spec.) That said, every enum type inherits from System.Enum and since we don't require a conforming implementation to override that type's ToString to presumably format the text differently in the absence/presence of this attribute, it is unspecified as what form the output from a call to ToString takes. Hence my earlier suggestion to close this Issue without action.

Now before you quickly agree, consider this: The only override of ToString that the C# spec requires is for System.Object. That is, we place no requirements whatsoever on how text is formatted for any other C# library type. However, many of our source code tests do expect and test for specific output content/format. Also note that I don't know what, if any, other library types might be impacted by this attribute's absence/presence.

From the CLI library spec:

The following example demonstrates the use of System.FlagsAttribute on the formatting of a System.Enum. With this attribute, the Position enumeration is used as a 4 bit-field, and the value 3 (Top | Left) is considered a valid value for the enumeration when formatting. Without this attribute, the enumeration Color is not used as a bit-field, and the value 3 (Red | Blue) is not considered a valid value for the enumeration when formatting.

using System;

[FlagsAttribute()]
public enum Position
{
    Top = 0x1,
    Left = 0x2,
    Bottom = 0x4,
    Right = 0x8
}

//enum Color declared without FlagsAttribute
public enum Color
{
    Red = 0x1,
    Blue = 0x2,
    Yellow = 0x4
}
public class enumFormat
{
    public static void Main()
    {
        Position p = Position.Top | Position.Left;
        Console.WriteLine("Position: {0}", p);
        Color c = Color.Red | Color.Blue;
        Console.WriteLine("Color: {0}", c);
    }
}

The output is

Position: Top, Left
Color: 3

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions