[c#] C# Enum - How to Compare Value

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.

This question is related to c# enums

The answer is


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

AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")

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.


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
}

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

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

Then

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