views:

147

answers:

5

I've got an enum with possible values:

    public enum Language
    {
        English = 1,
        French = 2,
        German = 3
    }

Now i want my class to be dynamic in the sense that it can cater for multiple values based on the enum list. So if the enum list grew i can capture all possible values.

Here's how my initial design looks:

    public class Locale
    {
        public string EnglishValue { get; set; }
        public string FrenchValue { get; set; }
        public string GermanValue { get; set; }
    }

But i want something that doesnt need to recompile if the enum list (or any list) grows: Is it possible to express something like:

    public class Locale
    {
        public string StringValue<T> Where T : Language
    }

I am open to any suggestions or design patterns that can nicely deal with this problem. Thanks

A: 

What you're proposing won't work unfortunately. This would be a better design IMHO:

public class Locale
{
    public string GetStringValue(Language language)
    {
        // return value as appropriate
    }
}
David M
A: 

Generic parameters are type parameters, not value parameters, and enum members (at least in C#) are distinct values, not types. The enum (in this case, Language) is indeed a type, but not its members.

Also, the generic class will know that it has a type parameter that is inherited from Language, but since enums are not inheritable in C#, this, and the generic type parameter constraint (the "where T:Langauge" thing) together pretty much mean that the generic type parameter will always be "Language" in all cases so there's no point having a generic class in this case. If I were you, I would do this:

public class Locale
{
    public string GetStringValue(Language language)
    {
        // ...
    }
}
DrJokepu
A: 

Maybe it's better for Language to be a class and incapsulate some of the language-specific processing just as System.Globalization.CultureInfo does?

Dmitry Ornatsky
A: 

While I agree with the other answers you could of course use a Dictionary for the Language list, then populate it from either a local config or database at runtime providing you with extensibility without the need for recompilation.

Lazarus
+1  A: 

Just use a Dictionary.

public class Locale : Dictionary<Language, string>
{
}

Whatever you do, if you change the enum, you have to recompile, but what you probably mean is "maintain" the Locale class.

Dave Van den Eynde
right, i mean to say maintain :p