C# - Enum.ToObject() Method with Example

In this tutorial, we will learn about the C# Enum.ToObject() method with its definition, usage, syntax, and example. By Nidhi Last updated : March 29, 2023

C# Enum.ToObject() Method

The Enum.ToObject() 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(s)

  • 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(s)

  • System.ArgumentException
  • System.ArgumentNullException

C# Example of Enum.ToObject() Method

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 »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.