Paul_T Paul_T - 1 month ago 11
C# Question

How to convert from a string to a Flags enum format in C#

I have this enum:

[Flags]
public enum Countries
{
None = 0,
USA = 1,
Mexico = 2,
Canada = 4,
Brazil = 8,
Chile = 16
}


I receive in input strings like these:

string selectedCountries = "Usa, Brazil, Chile";


how to convert it (in C#) back to:

var myCountries = Countries.Usa | Countries.Brazil | Countries.Chile;

Answer

Use Enum.Parse.

e.g. Countries c = (Countries)Enum.Parse(typeof(Countries), "Usa, Brazil...");