more elegant design about enum - c#

I'm on learning for C#.
I heared C# is one of the most constructible language. so would you guys make my code more elegant and efficient?
public class ISO639
{
public enum ISO639Code
{
Afrikaans, //af
Albanian, //sq
Amharic, //am
...
Yiddish, //yi
Unknown
}
public static string GetISO639CodeString(ISO639.ISO639Code l)
{
switch (l)
{
case ISO639Code.English: return "en";
case ISO639Code.Japanese: return "ja";
...
case ISO639Code.Hebrew: return "he";
default: return "";
}
public static ISO639.ISO639Code GetISO39CodeValue(string s)
{
switch (s)
{
case "ko" : return ISO639Code.Korean;
case "en" : return ISO639Code.English;
...
case "hu" : return ISO639Code.Hungarian;
default: return ISO639Code.Unknown;
}
}
}
Here is a my class ISO639. This class provides enum for ISO639 code, but I need a type conversion on from ISO639 enum to plain string. (ex. ISO639.ISO639Code.Italian => "it"). I also need a type conversion from plain string to ISO639 enum. (ex. "it" => ISO639.ISO639Code.Italian).
Is there a more efficient coding style for that?

You can add standard System.ComponentModel.Description attribute to each enum entry and then read it.
public enum ISO639Code
{
[Description("af")]
Afrikaans
}
public static class EnumExtensions
{
// Extension method to read Description value
public static string GetDescription(this Enum currentEnum)
{
var fi = currentEnum.GetType().GetField(currentEnum.ToString());
var da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
return da != null ? da.Description : currentEnum.ToString();
}
}
// **How-to read it**
ISO639Code isoCode = ISO639Code.Afrikaans;
// this will returns "af"
string isoDescription = isoCode.GetDescription();
EDIT:
string searchFor = "af";
ISO639Code foundEntry;
// Loop through all entries descriptions
var allEntries = Enum.GetValues(typeof(ISO639Code));
foreach (var entry in allEntries)
{
// If you will extract this as separate method and use it for search not only loop
// through the all entries - you can put here is yield return description
var currentEntry = ((ISO639Code)entry);
string description = currentEntry.GetDescription();
if (description == searchFor)
{
foundEntry = currentEntry;
break;
}
}

Sure. You can use attributes:
public enum ISO639Code
{
[CodeString("af")] Afrikaans,
[CodeString("sq")] Albanian,
}

Use dictionary, for example: new Dictionary<ISO639Code, string>.

I suggest you to use C# extension methods to enums, they allow you to add whatever logic you want.
For example, see http://pietschsoft.com/post/2008/07/c-enhance-enums-using-extension-methods.aspx

I'd simply store the information in a dictionary-like object. This way you can reference the name by key and get the value directly.

You have an enum:
public enum ISO639Code
{
Afrikaans = 1,
Albanian = 2,
Amharic = 3,
etc.
Create a database table:
ISO639Id int PK,
ISO639Code char(2)
Where the ISO639Id maps to the value of the enum.
In code you'd want a ISO630 Class containing Id and Code values read from the database.
(You can load this once and then cache it in memory.)
The beauty of this approach, is it can be easily extended so that if in future you wanted to store more pieces of information for each ISO639 code, you could simply add another field.

Look at System.Globailzation namespace. The functionality you require looks to be already implemented there. At worst you can see the architecture and technique applied in the .Net framework to solve a very similar problem.

Enumerations are really good to work in code, as they are really strongly typed and make refactoring easier.
Follow these steps:
Use attributes for whatever extra information you want to attach to an enum. Usually this is a simple Description attribute. Something like:
public enum IsoCodes
{
[Description("af")]
Africans = 0,
[Description("am")]
Americans = 1
}
Then write some extension methods to convert strings and integers to and from this enum:
public static string GetDescription(this Enum value)
{
var entries = value.ToString().Split(FlagEnumSeparatorCharacter);
var description = new string[entries.Length];
for (var i = 0; i < entries.Length; i++)
{
var fieldInfo = value.GetType().GetField(entries[i].Trim());
var attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
description[i] = (attributes.Length > 0) ? attributes[0].Description : entries[i].Trim();
}
return String.Join(", ", description);
}
public static int GetValue(this Enum value)
{
return (int)value.GetType().GetField(value.ToString()).GetRawConstantValue();
}
public static T ToEnum<T>(this string value)
{
if (typeof(T).BaseType.Name != typeof(Enum).Name)
{
throw new Exception("Not an enum");
}
return (T)Enum.Parse(typeof(T), value, true);
}
public static T ToEnum<T>(this int value)
{
if (typeof(T).BaseType.Name != typeof(Enum).Name)
{
throw new Exception("Not an enum");
}
return (T)Enum.ToObject(typeof(T), value);
}
Now use your enums as you like.

I would go with having ISO639Code as class instead of enum:
public class ISO639Code
{
public string Value { get; set ; }
public string Code { get; set; }
public ISO639Code()
{
this.Value = "";
this.Code = "";
}
public ISO639Code(string value, string code)
: this()
{
this.Value = value;
this.Code = code;
}
public override bool Equals(object obj)
{
if (obj != null)
{
if (obj is string)
return obj.ToString().Equals(this.Value, StringComparison.CurrentCultureIgnoreCase);
if (obj is ISO639Code)
return ((ISO639Code)obj).Value.Equals(this.Value, StringComparison.CurrentCultureIgnoreCase);
}
return false;
}
public override int GetHashCode()
{
return this.Value.GetHashCode();
}
public override string ToString()
{
return this.Value;
}
}
Then have global List<ISO639Code> with all possible codes, and to find specific code based on code name or value, just search for this in the List.
Personally, I prefer this over tweaking the enum.

Related

What is the efficient way to store and read additional information from enums

I was trying to store and retrieve additional information from enums. I ended up with 2 methods for it.
The first method is by using custom attributes.
https://stackoverflow.com/a/22054994/5078531
https://stackoverflow.com/a/35040378/5078531
public class DayAttribute : Attribute
{
public string Name { get; private set; }
public DayAttribute(string name)
{
this.Name = name;
}
}
enum Days
{
[Day("Saturday")]
Sat,
[Day("Sunday")]
Sun
}
public static TAttribute GetAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute
{
var enumType = value.GetType();
var name = Enum.GetName(enumType, value);
return enumType.GetField(name).GetCustomAttributes(false).OfType<TAttribute>().SingleOrDefault();
}
The second method I found here, by writing an extension method on enums.
https://stackoverflow.com/a/680515/5078531
public enum ArrowDirection
{
North,
South,
East,
West
}
public static class ArrowDirectionExtensions
{
public static UnitVector UnitVector(this ArrowDirection self)
{
switch(self)
{
case ArrowDirection.North:
return new UnitVector(0, 1);
case ArrowDirection.South:
return new UnitVector(0, -1);
case ArrowDirection.East:
return new UnitVector(1, 0);
case ArrowDirection.West:
return new UnitVector(-1, 0);
default:
return null;
}
}
}
If am looking for the performance which method should I choose ? or is there any other efficient methods which am missing?
Both are valid ways of implementing it; as are many other ways. Personally, I like the convenience of the first. The performance penalty of reflection can be mitigated by processing the attributes once only, and storing (presumably in a static field) - potentially as a flat array if the enum values are contiguous and 0-based; otherwise, perhaps in a dictionary.
You can make DayaAttributeCache more generic if you like such that it can store other enum and attribute types. I just did this quick to show a caching approach. Enum values have to be continuous starting at 0 but this can be changed to handle that case if needed.
public static class DaysAttributeCache
{
private static readonly string[] Cache;
static DaysAttributeCache()
{
Type enumType = typeof(Days);
Cache = new string[Enum.GetValues(enumType).Length];
foreach (Enum value in Enum.GetValues(enumType))
{
var name = Days.GetName(enumType, value);
DayAttribute attribute = enumType
.GetField(name)
.GetCustomAttributes(false)
.OfType<DayAttribute>()
.SingleOrDefault();
string weekDay = attribute?.Name;
Cache[((IConvertible)value).ToInt32(CultureInfo.InvariantCulture)] = weekDay;
}
}
public static string GetWeekday(this Days value)
{
return Cache[(int)value];
}
}
Called like this...
string saturday = Days.Sat.GetWeekday();

Generics, enums and custom attributes - is it possible?

Apologies for the amount of code, but it is easier to explain it this way.
I have a custom attribute CustomUserData implemented as follows:
public class CustomUserData : Attribute
{
public CustomUserData(object aUserData)
{
UserData = aUserData;
}
public object UserData { get; set; }
}
and an extension method for enums as:
public static class EnumExtensions
{
public static TAttribute GetAttribute<TAttribute>(this Enum aValue) where TAttribute : Attribute
{
Type type = aValue.GetType();
string name = Enum.GetName(type, aValue);
return type.GetField(name)
.GetCustomAttributes(false)
.OfType<TAttribute>()
.SingleOrDefault();
}
public static object GetCustomUserData(this Enum aValue)
{
CustomUserData userValue = GetAttribute<CustomUserData>(aValue);
return userValue != null ? userValue.UserData : null;
}
}
I then have a helper class that serializes/deserializes an enum that has custom data associated with it as follows:
public static class ParameterDisplayModeEnumListHelper
{
public static List<ParameterDisplayModeEnum> FromDatabase(string aDisplayModeString)
{
//Default behaviour
List<ParameterDisplayModeEnum> result = new List<ParameterDisplayModeEnum>();
//Split the string list into a list of strings
List<string> listOfDisplayModes = new List<string>(aDisplayModeString.Split(','));
//Iterate the enum looking for matches in the list
foreach (ParameterDisplayModeEnum displayModeEnum in Enum.GetValues(typeof (ParameterDisplayModeEnum)))
{
if (listOfDisplayModes.FindIndex(item => item == (string)displayModeEnum.GetCustomUserData()) >= 0)
{
result.Add(displayModeEnum);
}
}
return result;
}
public static string ToDatabase(List<ParameterDisplayModeEnum> aDisplayModeList)
{
string result = string.Empty;
foreach (ParameterDisplayModeEnum listItem in aDisplayModeList)
{
if (result != string.Empty)
result += ",";
result += listItem.GetCustomUserData();
}
return result;
}
}
however this is specific to ParameterDisplayModeEnum and I have a bunch of enums that I need to treat this way for serialization/deserialization so I would prefer to have a generic such as:
public static class EnumListHelper<TEnum>
{
public static List<TEnum> FromDatabase(string aDisplayModeString)
{
//Default behaviour
List<TEnum> result = new List<TEnum>();
//Split the string list into a list of strings
List<string> listOfDisplayModes = new List<string>(aDisplayModeString.Split(','));
//Iterate the enum looking for matches in the list
foreach (TEnum displayModeEnum in Enum.GetValues(typeof (TEnum)))
{
if (listOfDisplayModes.FindIndex(item => item == (string)displayModeEnum.GetCustomUserData()) >= 0)
{
result.Add(displayModeEnum);
}
}
return result;
}
public static string ToDatabase(List<TEnum> aDisplayModeList)
{
string result = string.Empty;
foreach (TEnum listItem in aDisplayModeList)
{
if (result != string.Empty)
result += ",";
result += listItem.GetCustomUserData();
}
return result;
}
}
However this will not work as GetCustomUserData() cannot be invoked. Any suggestions? I cannot change the use of the custom attribute or the use of the enums. I am looking for a generic way to do the serialization/deserialization without having to write a concrete list helper class each time.
All suggestions appreciated.
Try this code:
public static class EnumListHelper
{
private static void EnsureIsEnum<TEnum>()
{
if (!typeof(TEnum).IsEnum)
throw new InvalidOperationException(string.Format("The {0} type is not an enum.", typeof(TEnum)));
}
public static List<TEnum> FromDatabase<TEnum>(string aDisplayModeString)
where TEnum : struct
{
EnsureIsEnum<TEnum>();
//Default behaviour
List<TEnum> result = new List<TEnum>();
//Split the string list into a list of strings
List<string> listOfDisplayModes = new List<string>(aDisplayModeString.Split(','));
//Iterate the enum looking for matches in the list
foreach (Enum displayModeEnum in Enum.GetValues(typeof(TEnum)))
{
if (listOfDisplayModes.FindIndex(item => item == (string)displayModeEnum.GetCustomUserData()) >= 0)
{
result.Add((TEnum)(object)displayModeEnum);
}
}
return result;
}
public static string ToDatabase<TEnum>(List<TEnum> aDisplayModeList)
where TEnum : struct
{
EnsureIsEnum<TEnum>();
string result = string.Empty;
foreach (var listItem in aDisplayModeList.OfType<Enum>())
{
if (result != string.Empty)
result += ",";
result += listItem.GetCustomUserData();
}
return result;
}
}
var fromDatabase = EnumListHelper.FromDatabase<TestEnum>("test");
EnumListHelper.ToDatabase(fromDatabase);
UPDATE 0
To be clear, because we cannot restrict generics to Enum we should check that the type TEnum is an enum and throw an exception if it is not.
When we use the FromDatabase method we know that TEnum is enum, and we can write this code to cast an enum to the specified TEnum:
result.Add((TEnum)(object)displayModeEnum)
in the ToDatabase method we also know that TEnum is enum and we can write this code to convert TEnum to the Enum type:
aDisplayModeList.OfType<Enum>()
Ideally you'd want to restrict TEnum to Enum but that won't work as you can not restrict generics to Enum MicrosoftBut try following, it might do the trick...
if (listOfDisplayModes.FindIndex(item =>
item == (string)(displayModeEnum as Enum).GetCustomUserData()) >= 0)

How to define an enum with string value?

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 data source so whenever I add or remove from the Enum definition, I would not need to change anything in the combo box.
The problem is how can I define enum with string representation, something like:
public enum SeparatorChars{Comma = ",", Tab = "\t", 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();
}
You can achieve it but it will require a bit of work.
Define an attribute class which will contain the string value for enum.
Define an extension method which will return back the value from the attribute. Eg..GetStringValue(this Enum value) will return attribute value.
Then you can define the enum like this..
public enum Test : int {
[StringValue("a")]
Foo = 1,
[StringValue("b")]
Something = 2
}
To get back the value from Attribute Test.Foo.GetStringValue();
Refer : Enum With String Values In C#
As far as I know, you will not be allowed to assign string values to enum. What you can do is create a class with string constants in it.
public static class SeparatorChars
{
public static String Comma { get { return ",";} }
public static String Tab { get { return "\t,";} }
public static String Space { get { return " ";} }
}
For a simple enum of string values (or any other type):
public static class MyEnumClass
{
public const string
MyValue1 = "My value 1",
MyValue2 = "My value 2";
}
Usage: string MyValue = MyEnumClass.MyValue1;
Maybe it's too late, but here it goes.
We can use the attribute EnumMember to manage Enum values.
public enum UnitOfMeasure
{
[EnumMember(Value = "KM")]
Kilometer,
[EnumMember(Value = "MI")]
Miles
}
This way the result value for UnitOfMeasure 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 = " ";
}
A class that emulates enum behaviour but using string instead of int can be created as follows...
public class GrainType
{
private string _typeKeyWord;
private GrainType(string typeKeyWord)
{
_typeKeyWord = typeKeyWord;
}
public override string ToString()
{
return _typeKeyWord;
}
public static GrainType Wheat = new GrainType("GT_WHEAT");
public static GrainType Corn = new GrainType("GT_CORN");
public static GrainType Rice = new GrainType("GT_RICE");
public static GrainType Barley = new GrainType("GT_BARLEY");
}
Usage...
GrainType myGrain = GrainType.Wheat;
PrintGrainKeyword(myGrain);
then...
public void PrintGrainKeyword(GrainType grain)
{
Console.Writeline("My Grain code is " + grain.ToString()); // Displays "My Grain code is GT_WHEAT"
}
It is kind of late for answer, but maybe it helps someone in future. I found it easier to use struct for this kind of problem.
Following sample is copy pasted part from MS code:
namespace System.IdentityModel.Tokens.Jwt
{
//
// Summary:
// List of registered claims from different sources http://tools.ietf.org/html/rfc7519#section-4
// http://openid.net/specs/openid-connect-core-1_0.html#IDToken
public struct JwtRegisteredClaimNames
{
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Actort = "actort";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Typ = "typ";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Sub = "sub";
//
// Summary:
// http://openid.net/specs/openid-connect-frontchannel-1_0.html#OPLogout
public const string Sid = "sid";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Prn = "prn";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Nbf = "nbf";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Nonce = "nonce";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string NameId = "nameid";
}
}
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.
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"
}
I created a base class for creating string-valued enums in .NET. It is just one C# file that you can copy & paste into your projects, or install via NuGet package named StringEnum.
Usage:
///<completionlist cref="HexColor"/>
class HexColor : StringEnum<HexColor>
{
public static readonly HexColor Blue = New("#FF0000");
public static readonly HexColor Green = New("#00FF00");
public static readonly HexColor Red = New("#000FF");
}
Features
Your StringEnum looks somewhat similar to a regular enum:
// Static Parse Method
HexColor.Parse("#FF0000") // => HexColor.Red
HexColor.Parse("#ff0000", caseSensitive: false) // => HexColor.Red
HexColor.Parse("invalid") // => throws InvalidOperationException
// Static TryParse method.
HexColor.TryParse("#FF0000") // => HexColor.Red
HexColor.TryParse("#ff0000", caseSensitive: false) // => HexColor.Red
HexColor.TryParse("invalid") // => null
// Parse and TryParse returns the preexistent instances
object.ReferenceEquals(HexColor.Parse("#FF0000"), HexColor.Red) // => true
// Conversion from your `StringEnum` to `string`
string myString1 = HexColor.Red.ToString(); // => "#FF0000"
string myString2 = HexColor.Red; // => "#FF0000" (implicit cast)
Intellisense will suggest the enum name if the class is annotated with the xml comment <completitionlist>. (Works in both C# and VB): i.e.
Instalation
Either:
Install latest StringEnum NuGet package, which is based on .Net Standard 1.0 so it runs on .Net Core >= 1.0, .Net Framework >= 4.5, Mono >= 4.6, etc.
Or paste the following StringEnum base class to your project. (latest version)
public abstract class StringEnum<T> : IEquatable<T> where T : StringEnum<T>, new()
{
protected string Value;
private static IList<T> valueList = new List<T>();
protected static T New(string value)
{
if (value == null)
return null; // the null-valued instance is null.
var result = new T() { Value = value };
valueList.Add(result);
return result;
}
public static implicit operator string(StringEnum<T> enumValue) => enumValue.Value;
public override string ToString() => Value;
public static bool operator !=(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value != o2?.Value;
public static bool operator ==(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value == o2?.Value;
public override bool Equals(object other) => this.Value.Equals((other as T)?.Value ?? (other as string));
bool IEquatable<T>.Equals(T other) => this.Value.Equals(other.Value);
public override int GetHashCode() => Value.GetHashCode();
/// <summary>
/// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else throws InvalidOperationException.
/// </summary>
/// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
/// <param name="caseSensitive">If true, the strings must match case sensitivity.</param>
public static T Parse(string value, bool caseSensitive = false)
{
var result = TryParse(value, caseSensitive);
if (result == null)
throw new InvalidOperationException((value == null ? "null" : $"'{value}'") + $" is not a valid {typeof(T).Name}");
return result;
}
/// <summary>
/// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else returns null.
/// </summary>
/// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
/// <param name="caseSensitive">If true, the strings must match case sensitivity.</param>
public static T TryParse(string value, bool caseSensitive = false)
{
if (value == null) return null;
if (valueList.Count == 0) System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle); // force static fields initialization
var field = valueList.FirstOrDefault(f => f.Value.Equals(value,
caseSensitive ? StringComparison.Ordinal
: StringComparison.OrdinalIgnoreCase));
// Not using InvariantCulture because it's only supported in NETStandard >= 2.0
if (field == null)
return null;
return field;
}
}
For Newtonsoft.Json serialization support, copy this extended version instead. StringEnum.cs
I realized after the fact that this code is similar to Ben's answer. I sincerely wrote it from scratch. However I think it has a few extras, like the <completitionlist> hack, the resulting class looks more like an Enum, no use of reflection on Parse(), the NuGet package and repo where I will hopefully address incoming issues and feedback.
Building on some of the answers here I have implemented a reusable base class that mimics the behaviour of an enum but with string as the underlying type. It supports various operations including:
getting a list of possible values
converting to string
comparison with other instances via .Equals, ==, and !=
conversion to/from JSON using a JSON.NET JsonConverter
This is the base class in it's entirety:
public abstract class StringEnumBase<T> : IEquatable<T>
where T : StringEnumBase<T>
{
public string Value { get; }
protected StringEnumBase(string value) => this.Value = value;
public override string ToString() => this.Value;
public static List<T> AsList()
{
return typeof(T)
.GetProperties(BindingFlags.Public | BindingFlags.Static)
.Where(p => p.PropertyType == typeof(T))
.Select(p => (T)p.GetValue(null))
.ToList();
}
public static T Parse(string value)
{
List<T> all = AsList();
if (!all.Any(a => a.Value == value))
throw new InvalidOperationException($"\"{value}\" is not a valid value for the type {typeof(T).Name}");
return all.Single(a => a.Value == value);
}
public bool Equals(T other)
{
if (other == null) return false;
return this.Value == other?.Value;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
if (obj is T other) return this.Equals(other);
return false;
}
public override int GetHashCode() => this.Value.GetHashCode();
public static bool operator ==(StringEnumBase<T> a, StringEnumBase<T> b) => a?.Equals(b) ?? false;
public static bool operator !=(StringEnumBase<T> a, StringEnumBase<T> b) => !(a?.Equals(b) ?? false);
public class JsonConverter<T> : Newtonsoft.Json.JsonConverter
where T : StringEnumBase<T>
{
public override bool CanRead => true;
public override bool CanWrite => true;
public override bool CanConvert(Type objectType) => ImplementsGeneric(objectType, typeof(StringEnumBase<>));
private static bool ImplementsGeneric(Type type, Type generic)
{
while (type != null)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == generic)
return true;
type = type.BaseType;
}
return false;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken item = JToken.Load(reader);
string value = item.Value<string>();
return StringEnumBase<T>.Parse(value);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is StringEnumBase<T> v)
JToken.FromObject(v.Value).WriteTo(writer);
}
}
}
And this is how you would implement your "string enum":
[JsonConverter(typeof(JsonConverter<Colour>))]
public class Colour : StringEnumBase<Colour>
{
private Colour(string value) : base(value) { }
public static Colour Red => new Colour("red");
public static Colour Green => new Colour("green");
public static Colour Blue => new Colour("blue");
}
Which could be used like this:
public class Foo
{
public Colour colour { get; }
public Foo(Colour colour) => this.colour = colour;
public bool Bar()
{
if (this.colour == Colour.Red || this.colour == Colour.Blue)
return true;
else
return false;
}
}
I hope someone finds this useful!
What I have recently begun doing is using Tuples
public static (string Fox, string Rabbit, string Horse) Animals = ("Fox", "Rabbit", "Horse");
...
public static (string Comma, string Tab, string Space) SeparatorChars = (",", "\t", " ");
I wish there were a more elegant solution, like just allowing string type enum in the language level, but it seems that it is not supported yet. The code below is basically the same idea as other answers, but I think it is shorter and it can be reused. All you have to do is adding a [Description("")] above each enum entry and add a class that has 10 lines.
The class:
public static class Extensions
{
public static string ToStringValue(this Enum en)
{
var type = en.GetType();
var memInfo = type.GetMember(en.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
var stringValue = ((DescriptionAttribute)attributes[0]).Description;
return stringValue;
}
}
Usage:
enum Country
{
[Description("Deutschland")]
Germany,
[Description("Nippon")]
Japan,
[Description("Italia")]
Italy,
}
static void Main(string[] args)
{
Show(new[] {Country.Germany, Country.Japan, Country.Italy});
void Show(Country[] countries)
{
foreach (var country in countries)
{
Debug.WriteLine(country.ToStringValue());
}
}
}
Well first you try to assign strings not chars, even if they are just one character. use ',' instead of ",". Next thing is, enums only take integral types without char you could use the unicode value, but i would strongly advice you not to do so.
If you are certain that these values stay the same, in differnt cultures and languages, i would use a static class with const strings.
While it is really not possible to use a char or a string as the base for an enum, i think this is not what you really like to do.
Like you mentioned you'd like to have an enum of possibilities and show a string representation of this within a combo box. If the user selects one of these string representations you'd like to get out the corresponding enum. And this is possible:
First we have to link some string to an enum value. This can be done by using the DescriptionAttribute like it is described here or here.
Now you need to create a list of enum values and corresponding descriptions. This can be done by using the following method:
/// <summary>
/// Creates an List with all keys and values of a given Enum class
/// </summary>
/// <typeparam name="T">Must be derived from class Enum!</typeparam>
/// <returns>A list of KeyValuePair<Enum, string> with all available
/// names and values of the given Enum.</returns>
public static IList<KeyValuePair<T, string>> ToList<T>() where T : struct
{
var type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException("T must be an enum");
}
return (IList<KeyValuePair<T, string>>)
Enum.GetValues(type)
.OfType<T>()
.Select(e =>
{
var asEnum = (Enum)Convert.ChangeType(e, typeof(Enum));
return new KeyValuePair<T, string>(e, asEnum.Description());
})
.ToArray();
}
Now you'll have a list of key value pairs of all enums and their description. So let's simply assign this as a data source for a combo box.
var comboBox = new ComboBox();
comboBox.ValueMember = "Key"
comboBox.DisplayMember = "Value";
comboBox.DataSource = EnumUtilities.ToList<Separator>();
comboBox.SelectedIndexChanged += (sender, e) =>
{
var selectedEnum = (Separator)comboBox.SelectedValue;
MessageBox.Show(selectedEnum.ToString());
}
The user sees all the string representations of the enum and within your code you'll get the desired enum value.
Adding still something more as some of the answers here are missing the point of using enums. Naturally one option is is to have well defined strings as static variables etc, but then you're opening your interface for illegal values also, i.e. you need to validate the input. With enums it's guaranteed that only allowed values are passed to your interface.
enum Separator
{
Comma,
Tab,
Space,
CRLF,
SoFunny
}
In addition to this you can use e.g. an internal Dictionary for the mapping purposes.
private readonly Dictionary<Separator, string> separatorMap = new Dictionary<Separator, string>()
{
{ Separator.Comma, "," },
{ Separator.Tab, "\t" },
{ Separator.Space, " " },
{ Separator.CRLF, "\r\n" },
{ Separator.SoFunny, "Your Mom" }
};
Even more sophisticated method for doing this is to create a static class to give the enum new capabilities and handle the mapping there.
Example of using code above would be like.
public string TransformToSingleString(List<string> values, Separator separator)
{
var separateWith = separatorMap[separator];
...
}
Enumaration Class
public sealed class GenericDateTimeFormatType
{
public static readonly GenericDateTimeFormatType Format1 = new GenericDateTimeFormatType("dd-MM-YYYY");
public static readonly GenericDateTimeFormatType Format2 = new GenericDateTimeFormatType("dd-MMM-YYYY");
private GenericDateTimeFormatType(string Format)
{
_Value = Format;
}
public string _Value { get; private set; }
}
Enumaration Consuption
public static void Main()
{
Country A = new Country();
A.DefaultDateFormat = GenericDateTimeFormatType.Format1;
Console.ReadLine();
}
We can't define enumeration as string type. The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
If you need more details on enumeration please follow below link,that link will help you to understand enumeration.
Enumeration
#narendras1414
It works for me..
public class ShapeTypes
{
private ShapeTypes() { }
public static string OVAL
{
get
{
return "ov";
}
private set { }
}
public static string SQUARE
{
get
{
return "sq";
}
private set { }
}
public static string RECTANGLE
{
get
{
return "rec";
}
private set { }
}
}

Using localized enum as DataSource

I've lots of enums in my app. Most of them are used on combos like this:
Enum.GetValues(typeof(TipoControlador))
Now I'd like to localize them like this: Localizing enum descriptions attributes
How can I combine them? My first thought was to override the ToString method with an extension method, but that's not possible =(
Using the other article as a basis, you can create an extension method like this:
public static class LocalizedEnumExtensions
{
private static ResourceManager _resources = new ResourceManager("MyClass.myResources",
System.Reflection.Assembly.GetExecutingAssembly());
public static IEnumerable<string> GetLocalizedNames(this IEnumerable enumValues)
{
foreach(var e in enumValues)
{
string localizedDescription = _resources.GetString(String.Format("{0}.{1}", e.GetType(), e));
if(String.IsNullOrEmpty(localizedDescription))
{
yield return e.ToString();
}
else
{
yield return localizedDescription;
}
}
}
}
You would use it like this:
Enum.GetValues(typeof(TipoControlador)).GetLocalizedNames();
Technically, this extension method will accept any array, and you can't restrict it to only work on an enum, but you could add extra validation inside the extension method if you feel it's important:
if(!e.GetType().IsEnum) throw new InvalidOperationException(String.Format("{0} is not a valid Enum!", e.GetType()));
You have 2 problems here, the first is how to localize enums which is solved by Localizing enum descriptions attributes.
The second is how to display the localized name whilst using the enum's value. This can be solved by creating a simple wrapper object such as:
public sealed class NamedItem
{
private readonly string name;
private readonly object value;
public NamedItem (string name, object value)
{
this.name = name;
this.value = value;
}
public string Name { get { return name; } }
public object Value { get { return value; } }
public override string ToString ()
{
return name;
}
}
This provides a generic re-usable class for any drop down box where you might want to show a different name for an item than the item itself provides (eg enums, ints, etc).
Once you have this class, you can set the drop down's DisplayMember to Name and ValueMember to Value. This will mean that dropdown.SelectedValue will still return your enum.
I know this question is old, but this may help some people.
You can just handle the Format event of the ComboBox control (http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.format.aspx), and add your text logic in it.
private void ComboBoxFormat(object sender, ListControlConvertEventArgs e)
{
e.Value = GetDescription(e.Value);
}
public static string GetDescription(object item)
{
string desc = null;
Type type = item.GetType();
MemberInfo[] memInfo = type.GetMember(item.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
desc = (attrs[0] as DescriptionAttribute).Description;
}
}
if (desc == null) // Description not found
{
desc = item.ToString();
}
return desc;
}
With this, the ComboBox control still holds enum values rather than strings.

Possible to have strings for enums?

I want to have an enum as in:
enum FilterType
{
Rigid = "Rigid",
SoftGlow = "Soft / Glow",
Ghost = "Ghost",
}
How to achieve this? Is there a better way to do this? It's gonna be used for an instance of an object where it's gonna be serialized/deserialized. It's also gonna populate a dropdownlist.
using System.ComponentModel;
enum FilterType
{
[Description("Rigid")]
Rigid,
[Description("Soft / Glow")]
SoftGlow,
[Description("Ghost")]
Ghost ,
}
You can get the value out like this
public static String GetEnumerationDescription(Enum e)
{
Type type = e.GetType();
FieldInfo fieldInfo = type.GetField(e.ToString());
DescriptionAttribute[] da = (DescriptionAttribute[])(fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false));
if (da.Length > 0)
{
return da[0].Description;
}
return e.ToString();
}
No, but if you want to scope "const" strings and use them like an enum, here's what I do:
public static class FilterType
{
public const string Rigid = "Rigid";
public const string SoftGlow = "Soft / Glow";
public const string Ghost ="Ghost";
}
If you're comfortable with extension methods, you can easily do what you're after:
//Can return string constants, the results of a Database call,
//or anything else you need to do to get the correct value
//(for localization, for example)
public static string EnumValue(this MyEnum e) {
switch (e) {
case MyEnum.First:
return "First Friendly Value";
case MyEnum.Second:
return "Second Friendly Value";
case MyEnum.Third:
return "Third Friendly Value";
}
return "Horrible Failure!!";
}
This way you can do:
Private MyEnum value = MyEnum.First;
Console.WriteLine(value.EnumValue());
No, but you can cheat like this:
public enum FilterType{
Rigid,
SoftGlow,
Ghost
}
And then when you need their string values you can just do FilterType.Rigid.ToString().
Enums are always linked to an integer value. So no.
You can do FilterType.Rigid.ToString() to obtain the string value although it can't be localized directly.
You can get the Enum name as a string like this
FilterType myType = FilterType.Rigid;
String strType = myType.ToString();
However, you may be stuck with the Camel Case/Hungarian notation, but you can easily convert that to a more user friendly String using a method like this (Not the prettiest solution, I would be grateful for input on optimizing this):
Public Shared Function NormalizeCamelCase(ByVal str As String) As String
If String.IsNullOrEmpty(str) Then
Return String.Empty
End If
Dim i As Integer = 0
Dim upperCount As Integer = 0
Dim otherCount As Integer = 0
Dim normalizedString As String = str
While i < normalizedString.Length
If Char.IsUpper(normalizedString, i) Then
''Current char is Upper Case
upperCount += 1
If i > 0 AndAlso Not normalizedString(i - 1).Equals(" "c) Then
''Current char is not first and preceding char is not a space
''...insert a space, move to next char
normalizedString = normalizedString.Insert(i, " ")
i += 1
End If
ElseIf Not Char.IsLetter(normalizedString, i) Then
otherCount += 1
End If
''Move to next char
i += 1
End While
If upperCount + otherCount = str.Length Then
''String is in all caps, return original string
Return str
Else
Return normalizedString
End If
End Function
If that's still not pretty enough, you may want to look into Custom Attributes, which can be retrieved using Reflection...
In the System.ComponentModel namespace there is a class DescriptionAttribute that works well here.
enum FilterType
{
Rigid,
[Description("Soft / Glow")]
SoftGlow,
Ghost,
}
Then to get the description and fail over to the ToString()
var descriptionAttribute = Value.GetType()
.GetField(Value.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.OfType <DescriptionAttribute>()
.FirstOrDefault()??new DescriptionAttribute(Value.ToString());
This is not possible. C# only allows integral enum types (int, short, long, etc.). You can either create a lightweight "enum-like" class or use static constants.
static class FilterTypes
{
public const string Rigid = "Rigid";
// ...
}
// or ...
class FilterType
{
static readonly FilterType RigidFilterType = new FilterType("Rigid");
string name;
FilterType(string name) // private constructor
{
this.name = name;
}
public static FilterType Rigid
{
get { return FilterType.RigidFilterType; }
}
// ...
}
It is not outright possible. However you can fake it using an array.
First, Create you enum the way you would a regular one:
public enum Regexs
{
ALPHA = 0,
NUMERIC = 1,
etc..
}
Then you create an array that holds the values corresponding to the enum values:
private static string[] regexs = new string[]
{
"[A-Za-z]",
"[0-9]",
"etc"...
}
Then you can access your strings through the enum value:
public void runit(Regexs myregexEnum)
{
Regex regex = new Regex( regexs [(int)myregexEnum] );
}
No, it's not possible.
The approved types for an enum are
byte, sbyte, short, ushort, int, uint,
long, or ulong.
However, you can retrieve the declared name of an enum with the Enum class:
string name = Enum.GetName(typeof(FilterType), FilterType.Rigid);
If this doesn't work for you, a collection of string constants collected in a class might.
You can use an Attribute over the values
[System.ComponentModel.Description("Rigid")]
example:
enum FilterType
{
[System.ComponentModel.Description("Rigid")]
Rigid,
[System.ComponentModel.Description("Soft / Glow")]
SoftGlow,
[System.ComponentModel.Description("Ghost")]
Ghost
}
and use Reflection to get the descriptions.
Enum extension method:
public static string GetDescription(this Enum en)
{
var type = en.GetType();
var memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return en.ToString();
}
use it:
FilterType = FilterType.Rigid;
string description= result.GetDescription();
Along the lines of Shaun Bowe's example you can also do this in C# 3 with an extension method for enum (I did not come up with and cannot, for the life of me, remember where I did).
Create an Attribute:
public class DisplayTextAttribute : Attribute {
public DisplayTextAttribute(String text) {
Text = text;
}
public string Text { get; set; }
}
Create an extension:
public static class EnumHelpers {
public static string GetDisplayText(this Enum enumValue) {
var type = enumValue.GetType();
MemberInfo[] memberInfo = type.GetMember(enumValue.ToString());
if (memberInfo == null || memberInfo.Length == 0)
return enumValue.ToString();
object[] attributes = memberInfo[0].GetCustomAttributes(typeof(DisplayTextAttribute), false);
if (attributes == null || attributes.Length == 0)
return enumValue.ToString();
return ((DisplayTextAttribute)attributes[0]).Text;
}
}
I've found this to be really tidy solution.
In your enum add the following:
enum FilterType{
Rigid,
[DisplayText("Soft / Glow")]
SoftGlow,
Ghost
}
You could then access FilterType.GetDisplayText() which will pull back the string for the unattributed enums and the displayText for the ones with attributes.

Categories

Resources