-1

I am a programming novice. I would like to convert ComputerHand and PlayerHand to strings so I can then create an string array to write to a text file.

 public enum Hand { Rock = 1, Paper, Scissors };
 public enum Outcome { Win, Lose, Tie };

 public Hand ComputerHand { get; set; }
 public Hand PlayerHand { get; set; }
 public char UserSelection { get; set; }
NewbMilo
  • 49
  • 4
  • 4
    have you tried ComputerHand.ToString(). See here to iterate through all values : http://stackoverflow.com/questions/105372/enumerate-an-enum – PaulF Oct 01 '15 at 16:08
  • Possible duplicate of [Enum ToString with user friendly strings](http://stackoverflow.com/questions/479410/enum-tostring-with-user-friendly-strings) I use the method outlined here to provide friendly names. The `.ToString()` is fine if all you want is the name as it is defined - but sometimes that doesn't look particularly good if you want to use it in text. – user1666620 Oct 01 '15 at 16:10
  • I did consider mentioning deriving a converter from the TypeConverter class - but maybe not for novices. – PaulF Oct 01 '15 at 16:14
  • @PaulF it's nice to have the option though. – user1666620 Oct 01 '15 at 16:16
  • Just wanted to say that you may have a Hand array instead of storing all converted strings. Hand[] myHands; – borjab Oct 01 '15 at 17:25

1 Answers1

0

Given below Enum,

public enum AnEnum
{
    Value1,
    Value2,
    Value3
}

Short answer: AnEnum.Value1.ToString()

If you want to give a different details (friendlier string) to enum value, you can use "Description" attribute to enum. See this: How can I assign a string to an enum instead of an integer value in C#?

If you are dealing with enum <-> string, you may sometime want to convert string to an enum, which can be done like this:

AnEnum AnEnumValue = (AnEnum ) Enum.Parse(typeof(AnEnum ), "Value1", true);

Just for someone's benefit who is working with enum ans strings, if you want to make an array of string from enum values,

string[] arrayOfEnumStrings 
        = Enum.GetValues(typeof(AnEnum)).Cast<AnEnum>()
            .Select(enumVal=> enumVal.ToString()).ToArray();

Here, "Enum.GetValues(typeof(Foos)).Cast()" will get you enumurator of enum values. Then "Select" will convert those enum values to string.

Community
  • 1
  • 1
Yogee
  • 1,291
  • 13
  • 20