A_Rominger
A_Rominger

Reputation: 1

Restrict assignment of property to a set of constants in C#

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

Answers (2)

Grizzly
Grizzly

Reputation: 5943

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

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

Servy
Servy

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

Related Questions