Saturday, January 31, 2015

Restricted property value to list

If you want to be able to set the value of your property to only a set of predefined values at compile-time you could specify the type of the property as an enum:



public enum MyType
{
ValidValueOne,
ValidValueTwo
}

public class YourClass
{
public MyType MyProperty { get; set; }
}





If you want to restrict the values at run-time you could implement some logic in the setter of the property, e.g:



public class YourClass
{

private string _s;
public string MyProperty
{
get { return _s; }
set
{
if (value != "validvalue1" && value != "valuedvalue2")
throw new InvalidOperationException("invalid value");

_s = value;
}
}
}



Please remember to mark helpful posts as answer and/or helpful.

No comments:

Post a Comment