By forcing a variable to hold certain values ​​only

I am using vs 2012. I have a simple string property

 string _someString;

 public string MyString
  {
     get
       {
          return _someString;
       }

   }

      

I want this property to only contain specific values. So when a client uses this property, only those specific values ​​can be used.

+3


source to share


3 answers


It looks like what you really want enum

:

public enum MyValues //TODO rename all the things
{
    SomeValue,
    SomeOtherValue,
    FinalValue,
}

      

Then your property could be:



private MyValues value;
public  MyValues MyValue
{
    get { return value; }
}

      

If you need to get a string representation of that value, just call ToString

on the enum value:

string stringValue = value.ToString();

      

+3


source


Use enum as in:

enum MyEnum
{
AllowableValue#1,
AllowableValue#2,
...
}

public MyEnum myEnum { get; set; }

      



Then fill some UI element with only enumeration values.

+2


source


I assume you want to get some check on the setter and then:

public string MyString
{
    get
    {
        return _someString;
    }
    set
    {
        if (value == "a" || value == "b" /* ... */)
            _someString = value;
        else
            throw new InvalidArgumentException("Invalid value!");
    }
}

      

Make sure to set it via a property and not an actual member variable.

0


source







All Articles