Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading