Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my format giving me an error when I try to format an enum to a string?

Tags:

c#

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?

like image 609
Samantha J T Star Avatar asked Sep 16 '12 05:09

Samantha J T Star


People also ask

What is format enum?

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).

What does enum to string do?

TryParse Method (System) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

Can we convert enum to string in C#?

We can convert an enum to string by calling the ToString() method of an Enum.

How do you find the enum of a string representation?

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.


1 Answers

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");
like image 74
loopedcode Avatar answered Oct 10 '22 14:10

loopedcode