TheNewBegining TheNewBegining - 6 months ago 36
C# Question

Enum variable c#

This is my enum:

public enum SomeTest
{
Undefined = 0,
Gram = 1,
Kilogram = 2
}


And this is my Test class:

private SomeTest test;

public Test (SomeTest test)
{
this.test = test;
}


I want to set to
test
my
Settings.Default.Test
Is it possible?

asd = new Test(Test)

Answer Source

Since your Settings.Default.Test is a String, you can use Enum.Parse(..) for that:

asd = new Test(Enum.Parse(typeof(SomeTest),Settings.Default.Test))

When you run this in the csharp console:

csharp> public enum SomeTest
      > {
      >   Undefined = 0,
      >   Gram = 1,
      >   Kilogram = 2
      > }
csharp>  
csharp> Enum.Parse(typeof(SomeTest),"Gram")      
Gram

Note that it will throw an ArgumentException if the string does not match an enum value:

csharp> Enum.Parse(typeof(SomeTest),"Foo")  
System.ArgumentException: Requested value 'Foo' was not found.