Sunday 9 December 2018

c# - Enum with underlying type. Returning the string representation unintentionally




I have the following enum:




 public enum BikeType : byte
{
Road = 0,
Mountain = 1
};


When I try to pass it to a I retrieve the 'string' representation of the byte, not the numeric value:



string str = string.Format("Road bike has a byte value of {0}", BikeType.Road);




"Road bike has a byte value of Road"


I want the byte value (0). What am I doing wrong?



Thanks


Answer



You need to do casting to int




string str = 
string.Format("Road bike has a byte value of {0}", (int)BikeType.Road);


If you don't cast it it will call ToString on BikeType.Road which will return Road


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...