joeyanthon
joeyanthon

Reputation: 218

how to get default value in enum if not exists value

I have this enum:

public enum EnumMoney
{
    SDI= 1,
    RCV= 2,
    STIS= 3
}

if I retrieve the value with a non-existent code it returns the entire code.

Sample:

var selectedEnum =  (EnumMoney) 1;
var selectedEnumNoExist =  (EnumMoney) 200;

selectedEnumNoExist will return "200". I actually want it to return an empty string.

Upvotes: 2

Views: 3142

Answers (1)

Kaca992
Kaca992

Reputation: 2267

You need to use Enum.IsDefined static method to check if enum exists and then do something with it.

For example:


var someValue = 200;
var stringValue = Enum.IsDefined(typeof(EnumMoney), someValue) ? someValue.ToString() : "";

You can find more about Enum.IsDefined here: https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?view=net-5.0

Upvotes: 6

Related Questions