Click or drag to resize

EnumExtensionsToEnumT Method

Process a string and return an Enum value.

Read our blog on this topic: Effective Extensions, Part 2 – Extending Enums in C#

Namespace:  Xcalibur.Extensions
Assembly:  Xcalibur.Extensions (in Xcalibur.Extensions.dll) Version: 1.0.4.0 (1.0.0.0)
Syntax
public static T ToEnum<T>(
	this string str
)
where T : struct, new(), IConvertible

Parameters

str
Type: SystemString
string representing the enum

Type Parameters

T
The type of Enum

Return Value

Type: T
Enum value corresponding to the string value

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type String. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).
Exceptions
ExceptionCondition
ArgumentExceptionT must be an enumerated type
Examples
C#
 1/// <summary>
 2/// Thread-state type.
 3/// </summary>
 4public enum ThreadStateType
 5{
 6    [Description("Initialized")]
 7    Started = 0,
 8
 9    [Description("Ready")]
10    Waiting = 1,
11
12    [Description("Running")]
13    Processor = 2,
14
15    [Description("Standby")]
16    PreProcessor = 3,
17
18    [Description("Terminated")]
19    Ended = 4,
20
21    [Description("Wait")]
22    NotReady = 5,
23
24    [Description("Transition")]
25    WaitingForResource = 6,
26
27    [Description("Unknown")]
28    UndeterminedState = 7
29}
30
31/// <summary>
32/// Test method.
33/// </summary>
34public void ToEnumTest()
35{
36    // Get the "Processor" enum from the string "Processor"
37    ThreadStateType myType = ("Processor").ToEnum<ThreadStateType>();
38
39    // Returns: ThreadStateType.Processor
40}
See Also