Why does my format give me an error when I try to format an enumeration into a string?

I have the following listing:

public enum EReferenceKey { Accounts = 1, Emails = 3, Phones = 4 } 

When my enum pk variable is accounts and I try to convert it to "01" using

 var a = pk.ToString("00"); 

this gives me the following exception:

String format can only be "G", "g", "X", "x", "F", "f", "D" or "d"

Can someone explain what I'm doing wrong?

+6
source share
3 answers

You need to pass it to int before trying this format string. Enum has its own implementation of ToString, so your int format string is incorrect.

 var a = ((int)pk).ToString("00"); 
+6
source

Try casting to int before trying to format the enumeration value:

 var a = ((int)EReferenceKey.Accounts).ToString("00"); 

It worked for me.

+2
source

You are trying to use format characters for String.Format. The transfers are different. Take a look at http://msdn.microsoft.com/en-us/library/system.enum.format.aspx .

You should get the value and then format. Casting is the easiest way to do this.

+2
source

Source: https://habr.com/ru/post/925503/


All Articles