3

I have this method

public enum Values
{
    True= true,
    False=false
};
public static string GetValues(bool values)
{
    string status = "";
    switch (values)
    {
        case(bool)UIHelper.Values.False:

    }
}

I want to have this enum as boolean. It says, that:

Values cannot be casted as bool.

How can I do it so I can have it boolean?

15
  • 5
    0 and 1 map to false and true Commented Oct 20, 2016 at 13:49
  • 2
    If you want a boolean, then why not stick with using bool instead of an enum? Commented Oct 20, 2016 at 13:51
  • 2
    @CallumBradbury Actually zero maps to false and not zero maps to true. Commented Oct 20, 2016 at 13:51
  • 3
    @rory.ap that's what I said bro Commented Oct 20, 2016 at 13:53
  • 3
    @rory.ap Actually in C# no integer values map to bool. Also am I suppose to say Bro now? Commented Oct 20, 2016 at 13:57

4 Answers 4

8

Of course, you can map to 0 (Service) and 1 (Serial), but why map to that in the first place? Why not use bool from the start?

public static class UnlPointValues
{
    public const bool Serial = true;
    public const bool Service = false;
}

public static string GetUnloadingPointValues(bool values)
{
    string status = "";
    switch (values)
    {
        case UIHelper.UnlPointValues.Serial:

    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

If you have to stick to enum you can implement an extension method:

  public enum Values {
    True,
    False,
    // and, probably, some other options
  };

  public static class ValuesExtensions {
    public static bool ToBoolean(this Values value) {
      // which options should be treated as "true" ones
      return value == Values.False;
    }
  }

...

// you, probably want to check if UIHelper.Values is the same as values 
if (values == UIHelper.Values.ToBoolean()) {
  ...
}

Comments

1

I don't see that you need an enum here.

public static string GetUnloadingPointValues(bool isSerial)
{
    return isSerial ? "Serial" : "Service";
}

Or whatever string values you want to map.

Comments

0

Use 0 for false and 1 for true instead combined with Convert.ToBoolean

true if value is not zero; otherwise, false.

public enum UnlPointValues
{
    Serial = 1,  //true
    Service = 0  //false
};

public static string GetUnloadingPointValues(bool values)
{
    string status = "";
    switch (values)
    {
        case (Convert.ToBoolean((int)UIHelper.UnlPointValues.Serial)):
        break;
        case (Convert.ToBoolean((int)UIHelper.UnlPointValues.Service)):
        break;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.