11 February, 2011

WP7: Enum.GetNames not present?

It has really been a source of great pain, that “someone” forgot to put in the Enum.GetNames() method in the SL-subset of .NET. Only the Enum.GetName() is present!

Anyway – a utility class I found in a blog comment somewhere came in quite handy:

public class Enum<T>
{
public static IEnumerable<string> GetNames()
{
var type = typeof(T);

if (!type.IsEnum)
throw new ArgumentException("Type '" + type.Name + "' is not an enum");

return (from field in type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
where field.IsLiteral
select field.Name).ToList();
}
}

You use it like this:

var names = Enum<StockExchange>.GetNames();
ExchangeNames.AddRange(names);


(here the StockExchange is an enum.)



Technorati Tags:

No comments:

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...