C# Enum.GetName, GetNames: Get String Array From EnumUse the Enum.GetName and Enum.GetNames methods. Get strings and string arrays from an enum. 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. Method notes.
These methods require the typeof operator. They return a string or a string array. With GetNames, we can get many names at once.
The first argument to the Enum.GetName method is a Type. And this is easily provided with the result of the typeof operator.
And The second argument is an object: this object must be of the same type as the backing field for the enum. Here An int is provided (with the value 3) and the correct MedicationType is returned.
static void Main()
string name =
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.
Tip The typeof operator invokes reflection and the Enum.GetNames method also internally accesses the metadata representation in memory. Next This program shows how an enumerated type of medication types is accessed in a string array. Main Here Enum.GetNames() is invoked. Enum.GetNames does not use an instance of an enumeration to be called. GetNames This is a static method. We pass it a Type object as the parameter. The typeof expression returns that Type object.
static void Main()
// Get all enum names as strings.
var names =
// Write the enum names separated by a space.
Default Antipyretic Corticosteroid Cytotoxic Decongestant Expectorant
Performance. 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. Typeof parameter.
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 The typeof operator is a simple usage of reflection in that it accesses the program's metadata information. A summary. The Enum.GetName() method provides a way to get one string value based on an object value. It requires a type pointer. Summary, continued.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on 9/16/2022 (grammar).