Val Okafor Val Okafor - 1 month ago 7
C# Question

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.

Answer

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 Exception("no userProfile for this user"); // or any other exception
}
Comments