TheNewBegining
TheNewBegining

Reputation: 91

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)

Upvotes: 0

Views: 2709

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

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.

Upvotes: 3

Related Questions