C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: In this example, an int is provided (with the value 3) and the correct MedicationType is returned.
Typeof, nameofC# program that uses Enum.GetName
using System;
class Program
{
enum MedicationType
{
Default,
Antipyretic,
Corticosteriod,
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);
}
}
Output
Cytotoxic
Cytotoxic
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.
StaticC# program that uses Enum.GetNames
using System;
class Program
{
enum MedicationType
{
Default,
Antipyretic,
Corticosteriod,
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));
}
}
Output
Default Antipyretic Corticosteriod Cytotoxic Decongestant Expectorant
Typeof: The typeof operator is a simple usage of reflection in that it accesses the program's metadata information.
Tip: If you need to repeatedly use enum names, storing them in memory as a string[] is sometimes best.
Enum ToString