How to assign an object of class as string operator to variable?

Viewed 407

I have class which have properties.

For Example

class Caption
{  
   public string AR{get;set;}
   public string EN{get;set;}
   pbulic string Tu{get;set;}   
}

i want for example Assign Caption object to vairable directly without need to call property

I want use This

Caption caption=new Caption();
string myVar = caption;   // this will return EN property directly

Rather Than

string myVar = caption.En;

I don't know but i think there's overload string operator or something for targeted class itself.

Why i need this ? just for localization's purposes and more readability in localization object. rather every time creating switch(language) then assign caption.EN, Caption.AR. it will be ugly.

1 Answers

The cleanest way might be to implement an indexer. That way you can switch a single time, do whatever checks on the language, handle issues, deal with defaults, etc. inside the Caption class without the ceremony of calling a method, like so:

class Caption
{
    public string AR { get; set; }
    public string EN { get; set; }
    public string Tu { get; set; }

    // var cap = new Caption()[language];
    public string this[string language]
    {
        get
        {
            var which = AR;
            switch(language)
            {
                case nameof(EN):
                    which = EN;
                    break;
                case nameof(Tu):
                    which = Tu;
                    break;
            }
            return which;
        }
    }
}

Note that it's possible to achieve the syntax you're after where you can implicitly convert a Caption to a string. The caveat is that you'd need to know the language at some point before you do the conversion.

You can do so by providing a constructor that handles it on creation and/or with a method (chain-able if you wish) like I do below with For:

class Caption
{
    public string AR { get; set; }
    public string EN { get; set; }
    public string Tu { get; set; }

    // Gets the caption of the current language
    public string Current { get; private set; }

    // If the language is known in advance, you can return
    // the desired language directly.
    public static implicit operator string(Caption caption) 
        => caption.Current;

    public Caption For(string language)
    {
        var which = AR;
        switch (language)
        {
            case nameof(EN):
                which = EN;
                break;
            case nameof(Tu):
                which = Tu;
                break;
        }
        Current = which;
        return this;
    }
}

// Usage
var cap = new Caption
{ 
    AR = "Test-ar",
    EN = "Test-en",
    Tu = "Test-tu"        
}.For("EN");

string s = cap;
Console.WriteLine(s); // Test-en
Related