user8441630
user8441630

Reputation:

How to assign value from properties to enum C#

I have enum:

 public enum DiamDivide { Absolute, ByDivide }

and propertis with (Absolute, ByDivide) value from database.

public string CalcMethodName { get; set; }

How to assign value from string properties CalcMethodName to enum DiamDivide?

Upvotes: 0

Views: 235

Answers (3)

Peter Csala
Peter Csala

Reputation: 22679

Because database records could be compromised that's why blindly converting the string to an enum value might be error-prone.

A better approach could be to use TryParse and specify ignoring case:

if(Enum.TryParse<DiamDivide>(CalcMethodName, true, out var enumValue))
{
  //use enumValue
}

Even though it seems good, under the hood it uses reflection. So if the conversion is called many times then a single mapping would be better alternative:

private static readonly ImmutableDictionary<string, DiamDivide> Mapping = 
    new Dictionary<string, DiamDivide> {
        { nameof(DiamDivide.Absolute).ToLower(), DiamDivide.Absolute},
        { nameof(DiamDivide.ByDivide).ToLower(), DiamDivide.ByDivide}
    }.ToImmutableDictionary();

...
if (Mapping.ContainsKey(CalcMethodName.ToLower()))
{
  var enumValue = Mapping[CalcMethodName.ToLower()];
  //use enumValue
} 

Upvotes: 1

Lirzae
Lirzae

Reputation: 66

Convert string to enum

string calcMethodName = "Absolute";
DiamDivide diamdivide= Enum.Parse<DiamDivide>(calcMethodName);

Upvotes: 0

BFyre
BFyre

Reputation: 395

Above answer would work, you can also try this (.NET Core / .NET Framework ≥ 4.0 ):

Enum.TryParse(CalcMethodName, out DiamDivide diamDivide);
DiamDivide = diamDivide;

diamDivide is your parsed enum value. Also, the method itself returns bool which indicates if the provided value was succesfully parsed, so you can check for it:

if(Enum.TryParse(CalcMethodName, out DiamDivide diamDivide))
{
    DiamDivide = diamDivide;
}
else
{
    //log error
}

TryParse

Upvotes: 0

Related Questions