How can i have a c# enum that if i chose to string it returns a different string, like in java it can be done by
public enum sample{
some, other, things;
public string toString(){
switch(this){
case some: return "you choose some";
default: break;
}
}
}
Console.writeln(sample.some)
will output:
you choose some
i just want my enums to return a different string when i try to call them.
4) Enum constants are implicitly static and final and can not be changed once created.
Enums are types, so they should be named using UpperCamelCase like classes. The enum values are constants, so they should be named using lowerCamelCase like constants, or ALL_CAPS if your code uses that legacy naming style.
To my knowledge this is not possible. However, you can write an extension method that gets some other string:
public static class EnumExtensions
{
public static string ToSampleString(this SampleEnum enum)
{
switch(enum)
{
case SampleEnum.Value1 : return "Foo";
etc.
}
}
}
Now, just call this new ToSampleString
on instances of SampleEnum
:
mySampleEnum.ToSampleString();
If you are unfamiliar with extension methods in C#
, read more here.
Another option is to use an Description
attribute above each enum
value, as described here.
I would do it decoratively by creating an attribute e.g. Description and decorating the enum values with it.
e.g.
public enum Rate
{
[Description("Flat Rate")]
Flat,
[Description("Time and Materials")]
TM
}
Then use GetCustomAttributes
to read/display the values. http://msdn.microsoft.com/en-us/library/system.attribute.getcustomattributes.aspx
@CodeCamper Sorry about the late response but here is some example code to read the DescriptionAttribute:
Extension method:
public static class EnumExtensions
{
public static string Description<T>(this T t)
{
var descriptionAttribute = (DescriptionAttribute) typeof (T).GetMember(t.ToString())
.First().GetCustomAttribute(typeof (DescriptionAttribute));
return descriptionAttribute == null ? "" : descriptionAttribute.Description;
}
}
Usage:
Rate currentRate = Rate.TM;
Console.WriteLine(currentRate.Description());
You want a dictionary. An enumerator enumerates (gives a number) for its values. You want a string value to be returned when you provide a string key. Try something like:
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("some", "you choose some");
dictionary.Add("other", "you choose other");
dictionary.Add("things", "you choose things");
Then this code:
string value = dictionary["some"];
Console.writeln(value);
will return "you choose some"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With