I am trying to define an Enum
and add valid common separators which used in CSV or similar files. Then I am going to bind it to a ComboBox
as a dat
You can't, because enum can only be based on a primitive numeric type. You could try using a Dictionary instead:
Dictionary<String, char> separators = new Dictionary<string, char>
{
{"Comma", ','},
{"Tab", '\t'},
{"Space", ' '},
};
Alternatively, you could use a Dictionary<Separator, char>
or Dictionary<Separator, string>
where Separator
is a normal enum:
enum Separator
{
Comma,
Tab,
Space
}
which would be a bit more pleasant than handling the strings directly.
Maybe it's too late, but here it goes.
We can use the attribute EnumMember to manage Enum values.
public enum EUnitOfMeasure
{
[EnumMember(Value = "KM")]
Kilometer,
[EnumMember(Value = "MI")]
Miles
}
This way the result value for EUnitOfMeasure will be KM or MI. This also can be seen in Andrew Whitaker answer.
You can't do this with enums, but you can do it like that:
public static class SeparatorChars
{
public static string Comma = ",";
public static string Tab = "\t";
public static string Space = " ";
}
You can't - enum values have to be integral values. You can either use attributes to associate a string value with each enum value, or in this case if every separator is a single character you could just use the char
value:
enum Separator
{
Comma = ',',
Tab = '\t',
Space = ' '
}
(EDIT: Just to clarify, you can't make char
the underlying type of the enum, but you can use char
constants to assign the integral value corresponding to each enum value. The underlying type of the above enum is int
.)
Then an extension method if you need one:
public string ToSeparatorString(this Separator separator)
{
// TODO: validation
return ((char) separator).ToString();
}
For people arriving here looking for an answer to a more generic question, you can extend the static class concept if you want your code to look like an enum
.
The following approach works when you haven't finalised the enum names
you want and the enum values
are the string
representation of the enam name
; use nameof()
to make your refactoring simpler.
public static class Colours
{
public static string Red => nameof(Red);
public static string Green => nameof(Green);
public static string Blue => nameof(Blue);
}
This achieves the intention of an enum that has string values (such as the following pseudocode):
public enum Colours
{
"Red",
"Green",
"Blue"
}
You can achieve it but will required bit of work.
public enum Test : int { [StringValue("a")] Foo = 1, [StringValue("b")] Something = 2 }
Refer : Enum With String Values In C#