I have the following enum:
public enum EReferenceKey {
Accounts = 1,
Emails = 3,
Phones = 4
}
When my enum variable pk is Accounts and I try to convert this to "01" using
var a = pk.ToString("00");
it gives me the following exception:
Format String can be only "G", "g", "X", "x", "F", "f", "D" or "d"
Can someone explain what I am doing wrong?
The Format method converts value of a specified enumerated type to its equivalent string representation. Here you can also set the format i.e. d for Decimal, x for HexaDecimal, etc. We have the following enumeration. enum Stock { PenDrive, Keyboard, Speakers }; The default value gets assigned (initialize).
TryParse Method (System) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
We can convert an enum to string by calling the ToString() method of an Enum.
The Java Enum has two methods that retrieve that value of an enum constant, name() and toString(). The toString() method calls the name() method, which returns the string representation of the enum constant.
You need to cast it to int before attempting that format string. Enum has its own ToString implementation, as such your int format string is not correct.
var a = ((int)pk).ToString("00");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With