Consider this code:
public static class PredefinedStrings
{
public const string Golf = "Golfing";
public const string Basketball = "Basketball";
public const string HoolaHoops = "Hulahoops";
}
public class Sports
{
public string Name { get; set; }
}
How can I force the Name property of the Sports class to use only one of the PredifinedStrings?
Edit: I want to avoid using enums since the values always represent a string.
I would suggest using an
enuminstead:A typical assignment then would be
Even then it is not enforced since you still could do
Name = (SportName)42;but it is much harder to get wrong – but you could certainly put custom logic into the setter to filter out these invalid values.Also if you need the string representation of your enum value just use
ToString()on it.