0

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?

  • Make it an enumerable with a `DescriptionAttribute` – Yuriy Faktorovich Jul 05 '17 at 17:02
  • 1
    The best way I've seen it done is through the type-safe string enum pattern. You can see the implementation details [here](https://blog.falafel.com/introducing-type-safe-enum-pattern/) – Kolichikov Jul 05 '17 at 17:03
  • Yes, you examine the value on Set and throw if it isn't correct. If you want type safety, each string should be a sealed class of a certain base class. No, there isn't any way to really really prevent unallowed strings, unless you check them on set and throw. Even enums aren't vulnerable, as you can cast any applicable value to an enum no matter if it has values assigned to it. `enum foo { bar = 1; } foo whoops = (foo) 9001;` is completely valid code. –  Jul 05 '17 at 17:04
  • @YuriyFaktorovich Do you know if using an enum will mess with entityframework? – A_Rominger Jul 05 '17 at 17:10
  • @A_Rominger that's a different question but maybe [this](https://stackoverflow.com/questions/1526339/how-to-work-with-enums-in-entity-framework) can help you. – Grizzly Jul 05 '17 at 17:12
  • Possible duplicate of [c#:How to use enum for storing string constants?](https://stackoverflow.com/questions/1851567/chow-to-use-enum-for-storing-string-constants) – Grizzly Jul 05 '17 at 17:49

2 Answers2

1

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).

Servy
  • 202,030
  • 26
  • 332
  • 449
  • Why not mark this question as a duplicate if your answer is similar to the accepted one [here](https://stackoverflow.com/questions/1851567/chow-to-use-enum-for-storing-string-constants)? – Grizzly Jul 05 '17 at 17:42
  • @BviLLe_Kid Why didn't you mark the question as a duplicate, if you found a duplicate question? – Servy Jul 05 '17 at 17:46
  • I posted an answer before I researched storing constants variables in an enum, when I came across the Description Attribute which lead to a question having a similar answer answer as to what you posted. – Grizzly Jul 05 '17 at 17:49
  • @BviLLe_Kid So then why didn't you mark the answer as a duplicate when you eventually found the duplicate? Why did you assume someone that *didn't* see the duplicate would have closed the question as a duplicate of a question they didn't find? – Servy Jul 05 '17 at 17:50
  • Because I have seen where users are solely concerned with gaining more reputation for themselves even if their answer is similar, or even the exact same on questions that they either did/didn't see.. I'm not saying **you** specifically, but I have seen it in the past. Nevertheless I have flagged the question as a duplicate. – Grizzly Jul 05 '17 at 17:53
0

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.

Grizzly
  • 5,873
  • 8
  • 56
  • 109