Search code examples
c#.netenums

Looking for an example where the format string G yields a different output than the format string F (Enum format strings C#)


Here is a MRE:

FileAccessPermissions permissions = FileAccessPermissions.Read | FileAccessPermissions.Special;

Console.WriteLine(permissions.ToString("G"));
Console.WriteLine(permissions.ToString("F"));
Console.WriteLine(permissions.ToString("D"));
Console.WriteLine(permissions.ToString("X"));

[Flags]
enum FileAccessPermissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4, 
    Delete = 8,
    Special = 16,
    ReadWrite = Read | Write,
}

To my surprise, I can't find a singular example where the format specifier G and the F yield different outputs. I get this for this example:

Read, Special
Read, Special
17
00000011

If I do: FileAccessPermissions permissions = FileAccessPermissions.ReadWrite; I get:

ReadWrite
ReadWrite
3
00000003

Solution

  • If you remove the [Flags] attribute, then the two format specifiers will give you different values for eg: (FileAccessPermissions)17:

    FileAccessPermissions permissions = (FileAccessPermissions)17;
        
    Console.WriteLine(permissions.ToString("G"));
    Console.WriteLine(permissions.ToString("F"));
    Console.WriteLine(permissions.ToString("D"));
    Console.WriteLine(permissions.ToString("X"));
    
    enum FileAccessPermissions
    {
        None = 0,
        Read = 1,
        Write = 2,
        Execute = 4, 
        Delete = 8,
        Special = 16,
        ReadWrite = Read | Write,
    }
    

    Output:

    17
    Read, Special
    17
    00000011
    

    From the documentation:

    G or g

    If the Flags attribute isn't set, an invalid value is displayed as a numeric entry.

    F or f

    If the value can be displayed as a summation of the entries in the enumeration ... the string values of each valid entry are concatenated together, separated by commas.