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.
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.
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
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.
Detail 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 16, 2022 (grammar).