0

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)
3
  • 1
    What is your Settings.Default.Test? Commented Apr 13, 2017 at 11:10
  • Properties.Settings.Default.Test => type is string Commented Apr 13, 2017 at 11:12
  • @TheNewBegining What do you expect the behaviour of assigning a string to SomeTest to be? They're different types. Commented Apr 13, 2017 at 11:13

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

3 Comments

If I have a combobx and set to test my combobox's selected item, is it this simple as well?
@TheNewBegining: in that case you better use the values as an enum as datasource, like here.
@Willem Van Onsem can you please help me out in how we can handle this exception and return a default string in return.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.