Reputation: 8004
I have following statement in my code
string str = ((int)(UserRating)Enum.Parse(typeof(UserRating), ques.UserResponse)).ToString()
I need to store a number in str
. Something like "1", "2" or "3"
.
My Enum declaration is as below:
public enum UserRating
{
One = 1, Two, Three, Four, Five
}
Full statement is below:
UserResponse = (ques.Type == UserQuestionType.Rating ? ((int)Enum.Parse(typeof(UserRating), ques.UserResponse)).ToString() : ques.UserResponse)
Upvotes: 0
Views: 266
Reputation: 1789
If you want to get "1" from your enum try:
UserRating.One.ToString("d");
If you want to get "One" from your enum (easier to match perhaps) just omit the parameter in ToString()
:
UserRating.One.ToString();
And your full statement is altered like this:
UserResponse = (ques.Type == UserQuestionType.Rating ?
((UserRating)Enum.Parse(typeof(UserRating), ques.UserResponse)).ToString("d") : ques.UserResponse);
But be sure to test it on questions which type is equal to UserQuestionType.Rating
(or put any always true statement for testing)
Upvotes: 2
Reputation: 460138
Sometimes it helps to use more than one line:
UserRating userResponseEnum = (UserRating)Enum.Parse(typeof(UserRating), ques.UserResponse);
int userRatingValue = (int) userResponseEnum;
string str = userRatingValue.ToString();
Upvotes: 1
Reputation: 63327
Try this:
string str = ((int)Enum.Parse(typeof(UserRating), ques.UserResponse)).ToString();
You can cast an enum value to int
directly.
Upvotes: 2