Home > Net >  Using a switch statement within property set function with different types
Using a switch statement within property set function with different types

Time:12-22

I have the following field / property setup:

        private bool inpVariable;

        private bool InpVariable
        {
            get { return InpVariable; }
            set
            {
                switch (value)
                {
                    case "Yes":
                        InpVariable = true;
                        break;
                    case "No";
                        InpVariable = false;
                        break;
                    default:
                        InpVariable = false;
                        break;
                }
            }
        }

I'm getting the following error: Cannot implicitly convert type string to type bool.

I am trying to set the InpVariable using a constructor as follows:

        public inpClass(string inpVariable)
        {

            InpVariable = inpVariable;

        }

CodePudding user response:

The problem is you've declared InpVariable as a "bool".

You have many different alternatives. For example, you can declare a static method to convert text to boolean:

https://stackoverflow.com/a/2872750/421195

public static bool ToBoolean(this string str)
{
    return str.ToLower() == "yes";
}

bool answer = "Yes".ToBoolean(); // true
bool answer = "AnythingOtherThanYes".ToBoolean(); // false

Or you can define a class. Or an enum. Or write an extension method.

It really depends on how you want your application to USE "InpVariable".

  •  Tags:  
  • c#
  • Related