.Net Core 3.1 - How to use Enum to replace code string

Asked

Viewed 133 times

1

Separate file:

 public enum LANG { NOT_SET = 0, ENGLISH = 1, PORTUGUESE = 2 }

File in which I want to put Enum that is currently being validated with string:

public bool Validate(StructuralData data) {
    if ((int) (data.Language = GetLanguage()) <= 0)
        throw new Exception(
        "LANGUAGE variable not set properly, available languages:\n" + 
        "\"ENGLISH\" OR \"PORTUGUESE\"");

Briefly, I want to pass on what’s in Enum to what’s in string.

What I want is to be able to use the Enums, so that they can replace the string value that would be English or Portuguese, I want to put the Enum variable there and it returns me the same way in string only, through the variable.

  • format the part of the code to be more readable.

  • You want to change the message to use the Enum item name instead of the "ENGLISH" and "ENGLISH" constants"?

  • as I said, the validation is being done by a string, and I want to let it being made Enum appeal.

  • @Luizeradev No string validation shown in the code

  • It’s hard to understand what you want to do, you need to explain your question better.

2 answers

1

If understood correctly, to compare the value of an Enum you can convert to int or string:

(int)LANG.ENGLISH == 1

or

LANG.ENGLISH.ToString() == "ENGLISH"

If you want concatenate the values in the Exception who are in string you can use interpolation:

$"LANGUAGE variable not set properly, available languages:\n {LANG.ENGLISH} OR {LANG.PORTUGUESE}"

Interpolation will call the method ToString() available in your enumerator to format the string correctly.

I hope I’ve helped in some way.

0

I don’t know if I understand very well the purpose of your question, but if you want to compare the string with the Enum, you can use it this way:

string teste = "NOT_SET";       
Console.Write(LANG.NOT_SET.ToString() == teste); //True

If you no longer want to use the string, you can use your Enum number

Console.Write((int) LANG.ENGLISH ==  1); //True

Browser other questions tagged

You are not signed in. Login or sign up in order to post.