Reputation: 1
Say I had a property
public string RestrictedString {get; set;}
and I had a few static constant strings defined
public const string String1 = "First String";
public const string String2 = "Second String";
is there a way to only allow RestrictedString to be assigned to String1 or String2?
Upvotes: 0
Views: 1182
Reputation: 5943
using System;
using System.ComponentModel;
using System.Reflection;
public static class Program
{
public const string String1 = "First String";
public const string String2 = "Second String";
public enum RestrictedStrings
{
[Description("First String")]
String1,
[Description("Second String")]
String2
}
public static string GetDescription(Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((DescriptionAttribute)attrs[0]).Description;
}
}
return en.ToString();
}
public static void Main()
{
string description = Program.GetDescription(Program.RestrictedStrings.String1);
Console.WriteLine(description);
}
}
// Output: First String
Hopefully this helps.
Upvotes: 0
Reputation: 203829
Conceptually you're wanting to have a new type, so create a new Type that represents the valid values. In your case you want there to only be two possible valid values for your type, so construct those and don't allow any more to be constructed:
public class SomeMeaningfulName
{
private SomeMeaningfulName(string value)
{
Value = value;
}
public string Value { get; }
public static SomeMeaningfulName String1 = new SomeMeaningfulName("First String");
public static SomeMeaningfulName String2 = new SomeMeaningfulName("Second String");
}
Now you can change the type of that property to your new type, and know that it's only one of those two values (for which you can get the string value out of it).
Upvotes: 1