Enum.GetName
An enum
type has names. These names are string
representations of the enum
values. The .NET Framework provides the Enum.GetName
and Enum.GetNames
methods.
These methods require the typeof
operator. They return a string
or a string
array. With GetNames
, we can get many names at once.
GetName
exampleThe first argument to the Enum.GetName
method is a Type. And this is easily provided with the result of the typeof
operator.
enum
.int
is provided (with the value 3) and the correct MedicationType
is returned.using System; class Program { enum MedicationType { Default, Antipyretic, Corticosteroid, Cytotoxic, Decongestant, Expectorant }; static void Main() { string name = Enum.GetName(typeof(MedicationType), MedicationType.Cytotoxic); Console.WriteLine(name); name = Enum.GetName(typeof(MedicationType), 3); Console.WriteLine(name); } }Cytotoxic Cytotoxic
Enum.GetNames
This method also requires the Type pointer. This means you can pass it the typeof
(Identifier) where Identifier is the identifier for your enumerated type.
typeof
operator invokes reflection and the Enum.GetNames
method also internally accesses the metadata representation in memory.string
array.Enum.GetNames()
is invoked. Enum.GetNames
does not use an instance of an enumeration to be called.static
method. We pass it a Type object as the parameter. The typeof
expression returns that Type object.using System; class Program { enum MedicationType { Default, Antipyretic, Corticosteroid, Cytotoxic, Decongestant, Expectorant }; static void Main() { // Get all enum names as strings. var names = Enum.GetNames(typeof(MedicationType)); // Write the enum names separated by a space. Console.WriteLine(string.Join(" ", names)); } }Default Antipyretic Corticosteroid Cytotoxic Decongestant Expectorant
GetName
has internal checks that will reduce performance. If you are calling Enum.GetName
in a tight loop, using a cache or finding another approach would be beneficial.
The typeof
operator also uses a parameter, but the parameter is a Type identifier. The MedicationType
identifier is the name of the enum
and not an instance of the enum
.
typeof
operator is a simple usage of reflection in that it accesses the program's metadata information.The Enum.GetName()
method provides a way to get one string
value based on an object value. It requires a type pointer.
GetNames()
returns the entire collection of string
representations at once. If you need to use enum
names repeatedly, consider storing them as a string
array or list.