Lost_In_Library
Lost_In_Library

Reputation: 3493

How can I get values of enum variable?

My question is how can I get values of enum variable?

enter image description here Please look at the attached screenshot... "hatas" is a flag-enum. And I want to get "HasError" - "NameOrDisplayNameTooShort" errors to show them.

using System;

namespace CampaignManager.Enums
{
    [Flags]
    public enum CampaignCreaterUpdaterErrorMessage
    {
        NoError = 0,
        HasError = 1,
        NameOrDisplaynameTooShort = 2,
        InvalidFirstName = 3,
    }
}

I tried simply;

Messagebox.Show(hatas);  // it's showing InvalidFirstName somehow...

Thank you very much for any help...

Upvotes: 2

Views: 1154

Answers (3)

Paul Sasik
Paul Sasik

Reputation: 81527

First thing: If you want to use the FlagsAttribute on your enum you need to define the values in powers of two like this:

[Flags]
public enum CampaignCreaterUpdaterErrorMessage
{
    NoError = 0,
    HasError = 1,
    NameOrDisplaynameTooShort = 2,
    InvalidFirstName = 4,
}

To get parts of a flagged enum, try something like:

    var hatas = CampaignCreaterUpdaterErrorMessage.HasError | CampaignCreaterUpdaterErrorMessage.NameOrDisplaynameTooShort;
    var x = (int)hatas;

    for (int i=0; i<Enum.GetNames(typeof(CampaignCreaterUpdaterErrorMessage)).Length; i++)
    {
        int z = 1 << i; // create bit mask

        if ((x & z) == z) // test mask against flags enum
        {
            Console.WriteLine(((CampaignCreaterUpdaterErrorMessage)z).ToString());
        }
    }

For getting the underlying value try casting:

Messagebox.Show(((int)hatas)ToString());

In your example, ToString is getting called by default against the CampaignCreaterUpdaterErrorMessage enum which return the string representation of the enum.

By casting to an int, the underlying default type for enums, you get ToString on the integer value.

Upvotes: 2

CharleyXIV
CharleyXIV

Reputation: 1610

Try this:

Messagebox.Show(CampaignCreaterUpdaterErrorMessage.NameOrDisplaynameTooShort);

Upvotes: 0

user1274686
user1274686

Reputation:

You need to cast/unbox the enum into an int as follows.

(int)CampaignCreaterUpdaterErrorMessage.NoError 
(int)CampaignCreaterUpdaterErrorMessage.HasError 

Upvotes: 1

Related Questions