Sunday, December 9, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...