I would like a class to store a default string, and also store translated values for that string. The results will be stored in json. I'm looking for a peer review on how this could be improved.
My biggest problem with this is to get the string value from the class you have to use the concrete type, using var will return the object.
Translatable String Class
namespace OpenPartsBook
{
[Serializable()]
public class TranslatableString
{
[JsonProperty]
private string Text;
public List<Translation> Translations { get; set; }
public TranslatableString()
{
Translations = new List<Translation>();
}
public TranslatableString(string value)
{
Translations = new List<Translation>();
Text = value;
}
/// <summary>
/// Get a translation for the string by walking up the translation hierarchy
/// if the requested language is not found it returns the default
/// uses ISO 3166/ISO 3166-2
/// </summary>
/// <param name="LanguageCode">string - language code</param>
/// <returns>string</returns>
public string ToTranslatedString(string LanguageCode)
{
string temp = String.Empty;
int i = LanguageCode.Length;
if (this.Translations.Any(t => t.LanguageCode.ToLower().Equals(LanguageCode.ToLower())))
{
temp = this.Translations.First(t => t.LanguageCode.ToLower().Equals(LanguageCode.ToLower())).Text;
}
else
{
while ((i = LanguageCode.LastIndexOf("-", i)) != -1)
{
var code = LanguageCode.Substring(0, i).ToLower();
if (this.Translations.Any(t => t.LanguageCode.ToLower().Equals(code.ToLower())))
{
temp = this.Translations.First(t => t.LanguageCode.ToLower().Equals(code.ToLower())).Text;
break;
}
--i;
}
}
if (String.IsNullOrEmpty(temp)) temp = Text;
return temp;
}
public static implicit operator TranslatableString(string s)
{
return s == null ? null : new TranslatableString(s);
}
public static implicit operator string(TranslatableString s) { return s.ToString(); }
public override string ToString() { return Text; }
}
}
Translation Class
namespace OpenPartsBook
{
[Serializable()]
[DataContract]
public class Translation
{
[DataMember(Name = "languageCode", IsRequired = true)]
public string LanguageCode { get; set; }
[DataMember(Name = "text", IsRequired = true)]
public string Text { get; set; }
public Translation()
{
}
}
}
Resulting Json:
"Title": {
"Text": "Radiator",
"Translations": [
{
"languageCode": "es",
"text": "radiador"
},
{
"languageCode": "fr",
"text": "radiateur"
}
]
}