So I need to get a List<string>
from my enum
Here is what I have done so far:
enum definition
[Flags]
public enum ContractorType
{
[Description("Recipient")]
RECIPIENT = 1,
[Description("Deliver")]
DELIVER = 2,
[Description("Recipient / Deliver")]
RECIPIENT_DELIVER = 4
}
HelperClass with method to do what I need:
public static class EnumUtils
{
public static IEnumerable<string> GetDescrptions(Type enumerator)
{
FieldInfo[] fi = enumerator.GetFields();
List<DescriptionAttribute> attributes = new List<DescriptionAttribute>();
foreach (var i in fi)
{
try
{
yield return attributes.Add(((DescriptionAttribute[])i.GetCustomAttributes(
typeof(DescriptionAttribute),
false))[0]);
}
catch { }
}
return new List<string>{"empty"};
}
}
Now in the line where I yield
values, I got a NullReferenceException
. Did I miss something? The syntax looks all right to me, but maybe I overlooked something?
Edit: I'm using .net Framework 4.0 here.
It think this can solve your problem. If it is not implemented you can return
null
or an exception. It depends what you need.So you will use it like this :
Sorry that I didn't read your question. Here is some code that you can use to take all of the description strings:
You need to find the
DescriptionAttribute
on each field, if it exists and then retrieve theDescription
attribute e.g.If you could have multiple descriptions on a field, you could do something like:
which is more similar to your existing approach.
I created these extension methods
Usage
Will return a
Dictionary<TestEnum, string>
with value as keys and descriptions as values. If you want just a list, you can change.ToDictionary
toHere is a small reusable solution. This is an abstract class which will extract all the attributes of type K from type T.
Should we now want to extract only attributes of
DescriptionAttribute
type, we would use the following class.This class will extract only attributes of
DescriptionAttribute
type from the typeT
. But to actually use this class in you context you will simply need to do the following.This line of code will write out all the descriptions you used as parameters in your attributes of type
DescriptionAttribute
. Should you need to extract some other attributes, just create a new class that derives from theAbstractAttributes<T, K>
class and close its typeK
with the appropriate attribute.You can try this
This generic static method works fine for getting a list of descriptions for each value of an enum type of T: