How to get elements from simple array in C#?
I need to get values of my enum, so I am using following com开发者_开发知识库mand:
Array a = Enum.GetValues(typeof(Typ));
However, typical expression a[x] does not work, why?
Thanks
Well, because Enum.GetValues
is not generic.
If you write:
var a = Enum.GetValues(typeof(Typ));
Console.WriteLine(a.GetType());
You'll get: "Namespace.Typ[]". But because method is not generic, compiler can't change returning type basing on supplied type, so the method returns System.Array
which is base type for arrays and you have to use type casts to downcast it to expected type, for example:
Typ[] a = (Typ[])Enum.GetValues(typeof(Typ));
The proper way in my opinion to do it is:
Array a = Enum.GetValues(typeof(Typ));
and then retrieve elements at positions by:
a.GetValue(elementsIndex);
I've used the following code to handle emums when converting a custom classes for DB SP params, works all the time.
public static object ParamValue<T>(Enum value)
{
if (value == null)
return System.DBNull.Value;
else
return (T)Enum.Parse(value.GetType(), value.ToString());
}
Based on OPs comments, he might not actually be interested in the values of the Enum
, but instead of the names. The distinction can easily be confusing to beginners. Tip: When you ask questions involving an error (i.e. "does not work, why?"), then including the error message often helps.
If you are looking for the names in the Enum
, try:
string[] names = Enum.GetNames(typeof(Typ));
精彩评论