C# Enum TryParse(String, Boolean, TEnum)

Description

Enum TryParse(String, Boolean, TEnum)converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.

Syntax

Enum.TryParse(String, Boolean, TEnum) has the following syntax.


public static bool TryParse<TEnum>(
  string value,//from   w  w w .j av a 2 s . co m
  bool ignoreCase,
  out TEnum result
)
where TEnum : struct

Parameters

Enum.TryParse(String, Boolean, TEnum) has the following parameters.

  • TEnum - The enumeration type to which to convert value.
  • value - The string representation of the enumeration name or underlying value to convert.
  • ignoreCase - true to ignore case; false to consider case.
  • result - When this method returns, result contains an object of type TEnum whose value is represented by value if the parse operation succeeds. If the parse operation fails, result contains the default value of the underlying type of TEnum. Note that this value need not be a member of the TEnum enumeration. This parameter is passed uninitialized.

Returns

Enum.TryParse(String, Boolean, TEnum) method returns true if the value parameter was converted successfully; otherwise, false.

Example

The following example defines a Colors enumeration, calls the TryParse(String, Boolean, TEnum) method to convert strings to their corresponding enumeration values


//  w  ww .  ja v a  2 s . co  m
using System;

[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };

public class Example
{
   public static void Main()
   {
      string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
      foreach (string colorString in colorStrings)
      {
         Colors colorValue;
         if (Enum.TryParse(colorString, true, out colorValue))        
            Console.WriteLine(colorValue);
         else
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
      }
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version