An alternative to Strings?

Asked

Viewed 61 times

0

Several things in the project have a table with possible names (strings). But I don’t want to use strings to make comparisons for various reasons (case-sensitive, typo, name table changes, etc). So I wanted to use enums, but C# only lets Overload on class operators, not enums. I can even make a function to compare a string with a corresponding Enum, but I wanted a more elegant solution.

if("nome" == tipoEnum.fulano)

would look better than

if(funcaoDeComparar(string, enum))
  • 1

    You say you don’t want to use strings, but that’s what you’re wearing, I don’t understand.

1 answer

2

You could create constants and use these constants for comparison, for example:

const string NOME1 = "Fulano";
if ("nome" == NOME1)
...

Another option would be to use Enum as you said and in comparison do:

if ("nome" == tipoEnum.fulano.ToString())

A third option would be to convert the string to Enum and then compare it to Enum or switch. Here’s an example of converting a string to Enum:

private Enum_ItemType ConvertItemTypeStringToEnum(string itemTypeString)
    {
        Enum_ItemType itemType;

        if (string.IsNullOrEmpty(itemTypeString))
        {
            return Enum_ItemType.Unidentified;
        }
        else
        {
            try
            {
                System.Enum.TryParse<Enum_ItemType>(itemTypeString, out itemType);
            }
            catch (Exception)
            {
                itemType = Enum_ItemType.Unidentified;
            }
        }

        return itemType;
    }

Browser other questions tagged

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