C# Enum - How to Compare Value
Asked Answered
C

5

47

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.

Cozen answered 23/10, 2013 at 8:50 Comment(5)
Are you sure userProfile is not null?Batfish
Why the numbers for the enum values? Enums tend to only need numeric equivalents if you are using them as bit flags and can probably be removed in this case.Australian
enums can be compared without converting it to string, also the exception might be coming from the instance userProfileValais
@Stony looks like it, I am going through to see why userProfile is nullCozen
@ValOkafor just to your knowledge I have added the code to prevent the if statement from runing when userProfile is nullRelevance
F
68

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
}
Finery answered 23/10, 2013 at 8:51 Comment(4)
If userProfile.AccountType field (property) is of AccountType type, then it can't be null, because enums are not nullable in C#. I'd rather bet that userProfile itself is null.Reservoir
It's probably the userProfile that is null, because AccountType is an enum, thus value type, and cannot be null (unless it is explicitly made Nullable)Cyclometer
If I would like to compare two Enums. Would it throw some exception? if yes , then what would be exception how it could be handledDuckworth
I have got exception while comparing enum values. May I use .Equals to compare rather than " == " to get rid of exception. Here it is Exception what i got. Failed to compare two elements in the array. System.Collections.Generic.GenericArraySortHelper1.BinarySearch(T[] array, Int32 index, Int32 length, T value, IComparer1 comparer) at System.Array.BinarySearch[T](T[] array, Int32 index, Int32 length, T value, IComparer`1 comparer) at System.Array.BinarySearch[T] at System.RuntimeType.GetEnumName(Object value) at System.Enum.InternalFormat(RuntimeType eT, Object value)Duckworth
L
11

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

AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")
Lalalalage answered 23/10, 2013 at 8:53 Comment(1)
Although technically possible, it's not advisable for speed, localization and other issues.Michikomichon
R
9

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
}
Relevance answered 23/10, 2013 at 8:52 Comment(3)
Thank you, that worked, but I am still getting a Null reference, so I stepping through my Login logicCozen
@ValOkafor check my explainationFinery
@ValOkafor as wudzik stated you are probably refering to not-initalized userProfile, so either make sure it's initalized before the conditio is checked or add the following code (added to answer).Relevance
A
9

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.

Agro answered 14/2, 2015 at 14:39 Comment(0)
P
3

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

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

Then

if (userProfile?.AccountType == accountType)
{
    //your code
}
Pompey answered 12/3, 2019 at 8:57 Comment(1)
I'm not a fan of enum any more due to all of these conversions. I now just do a public class with public const int for each value, then no conversion needed.Tucky

© 2022 - 2024 — McMap. All rights reserved.