Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Enum - How to Compare Value

Tags:

c#

enums

How can I compare the value of this enum

public enum AccountType
{
    Retailer = 1,
    Customer = 2,
    Manager = 3,
    Employee = 4
}

I am trying to compare the value of this enum in an MVC4 controller like so:

if (userProfile.AccountType.ToString() == "Retailer")
{
    return RedirectToAction("Create", "Retailer");
}
return RedirectToAction("Index", "Home");

I also tried this

if (userProfile.AccountType.Equals(1))
{
    return RedirectToAction("Create", "Retailer");
}
return RedirectToAction("Index", "Home");

In each case I get an Object reference not set to an instance of an object.

like image 683
Val Okafor Avatar asked Oct 23 '13 08:10

Val Okafor


5 Answers

use this

if (userProfile.AccountType == AccountType.Retailer)
{
     ...
}

If you want to get int from your AccountType enum and compare it (don't know why) do this:

if((int)userProfile.AccountType == 1)
{ 
     ...
}

Objet reference not set to an instance of an object exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.

EDIT (thanks to @Rik and @KonradMorawski) :

Maybe you can do some check before:

if(userProfile!=null)
{
}

or

if(userProfile==null)
{
   throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}
like image 93
Kamil Budziewski Avatar answered Oct 08 '22 04:10

Kamil Budziewski


You can use Enum.Parse like, if it is string

AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")
like image 24
Satpal Avatar answered Oct 08 '22 03:10

Satpal


Comparision:

if (userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:

if(userProfile != null)
{
    if (userProfile.AccountType == AccountType.Retailer)
    {
       //your code
    }
}

or shorter version:

if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
    //your code
}
like image 42
Tafari Avatar answered Oct 08 '22 05:10

Tafari


You can use extension methods to do the same thing with less code.

public enum AccountType
{
    Retailer = 1,
    Customer = 2,
    Manager = 3,
    Employee = 4
}

static class AccountTypeMethods
{
    public static bool IsRetailer(this AccountType ac)
    {
        return ac == AccountType.Retailer;
    }
}

And to use:

if (userProfile.AccountType.isRetailer())
{
    //your code
}

I would recommend to rename the AccountType to Account. It's not a name convention.

like image 45
Dherik Avatar answered Oct 08 '22 04:10

Dherik


You should convert the string to an enumeration value before comparing.

Enum.TryParse("Retailer", out AccountType accountType);

Then

if (userProfile?.AccountType == accountType)
{
    //your code
}
like image 32
Ayberk Avatar answered Oct 08 '22 04:10

Ayberk