Snake Eyes
Snake Eyes

Reputation: 16764

Use set of string constants into class or struct and use it as parameter to method C#

I have a list of languages like

public ??struct?? Language {
    Arabic = "ar"
    Brazilian = "br"
    Bulgarian = "bg"
    Cantonese = "hk"
    Croatian = "hr"
    Czech = "cz"
    Danish = "dk"
    Dutch = "nl"
    English = "uk"
    ...
}

I want to use a struct with those languages as Language and use it as parameter in a method like

void SetLanguage(Language lang) {
   if(lang == Language.Arabic) { ... }
}

Cannot use enums since they accepts only integer values. I didn't use never the struct and don't know how to achieve my goal...

Let me know if something is not clear.

Upvotes: 1

Views: 55

Answers (1)

Sean
Sean

Reputation: 62492

You can use a class with a private constructor and a series of public fields for each language:

sealed class Language
{
    public static readonly Language Arabic = new Language("ar");
    public static readonly Language Brazilian = new Language("br");

    private Language(string name)
    {
        this.Name = name;
    }

    public string Name{get;}
}

By making the constructor private you've got complete control over the number and configuration of each instance.

Upvotes: 6

Related Questions