Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Enum.GetValues and Enum.GetNames

Tags:

c#

.net

I see the Enum.GetValues returns base Array type and Enum.GetNames returns a string array. But I don't understand how this is very significant. For an enum anyways, the values are strings.

But, there is an associated problem. The DataGridView ComboBox column databinds to an enum if I give the DataSource = Enum.GetValues, but it doesn't databind when I give it Enum.GetNames as a DataSource.

like image 694
Everything Matters Avatar asked Nov 27 '11 01:11

Everything Matters


People also ask

What does enum GetValues return?

The GetValues method returns an array that contains a value for each member of the enumType enumeration. If multiple members have the same value, the returned array includes duplicate values.

Can you forEach an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

What is enum method in C#?

Enums in C# The enum keyword in C# declares a list of named integer constants. An enum can be defined in a namespace, structure or class. However, it is better to define it in a namespace so that all the classes can access it.


2 Answers

GetValues will return an Array of the underlying integer values for each item in the Enum.

GetNames will return a string array of the Names for the items in the enum.

The Array returned by GetValues implements IList while the string[] returned by GetNames does not, which explains the binding differences.

like image 97
competent_tech Avatar answered Sep 20 '22 20:09

competent_tech


Enums are actually numeric. GetNames returns the field names. GetValues returns the numeric values.

MSDN has a great sample on GetValues.

like image 45
Daniel A. White Avatar answered Sep 20 '22 20:09

Daniel A. White