Home »
.Net »
C# Programs
C# program to demonstrate the use of ToObject() method of Enum class
Here, we are going to demonstrate the use of ToObject() method of Enum class in C#.Net.
Submitted by Nidhi, on April 17, 2021
Here, we will learn about the ToObject() method of the Enum class. This method is used to convert the value to an object that can be typecast to an enum object. This is nine times overloaded method.
Syntax:
object Enum.ToObject(Type enumType, Byte value);
object Enum.ToObject(Type enumType, Int16 value);
object Enum.ToObject(Type enumType, Int32 value);
object Enum.ToObject(Type enumType, Int64 value);
object Enum.ToObject(Type enumType, Object value);
object Enum.ToObject(Type enumType, SByte value);
object Enum.ToObject(Type enumType, UInt16 value);
object Enum.ToObject(Type enumType, UInt32 value);
object Enum.ToObject(Type enumType, UInt64 value);
Parameter:
- enumType : Type of enum object.
- value : Value to be converted to object.
Return value:
This method returns the object on the basis of the passed value.
Exception:
- System.ArgumentException
- System.ArgumentNullException
Program:
The source code to demonstrate the use of ToObject() method of Enum class is given below. The given program is compiled and executed successfully.
using System;
class Sample
{
enum Directions { EAST=0,WEST=1,NORTH=2,SOUTH=3};
//Entry point of Program
static public void Main()
{
Directions dir;
Byte value1 = 1;
Int16 value2 = 2;
Int32 value3 = 3;
//ToObject with Byte value
dir = (Directions)Enum.ToObject(typeof(Directions), value1);
Console.WriteLine(Enum.GetName(typeof(Directions),dir));
//ToObject with Int16 value
dir = (Directions)Enum.ToObject(typeof(Directions), value2);
Console.WriteLine(Enum.GetName(typeof(Directions), dir));
//ToObject with Int32 value
dir = (Directions)Enum.ToObject(typeof(Directions), value3);
Console.WriteLine(Enum.GetName(typeof(Directions), dir));
}
}
Output:
WEST
NORTH
SOUTH
Press any key to continue . . .
C# Enum Class Programs »