Multi-lingual string property in C#

Couple of months back I had a situation where I needed a single property (lets say Title) for each language currently being viewed.

Its a pretty big pain defining separate properties for every language, like for Title_En, Title_ar etc. So an idea came into my mind why not to define a class which will serve as a single string property but return a value according to the current culture/language of the page.

Below is the class I defined:

public class LString
{
Dictionary<string, string> values = new Dictionary<string, string>();

public Dictionary<string, string> Values
{
get { return values; }
set { values = value; }
}

public string this[string culture]
{
get
{
string result = string.Empty;
if (values.ContainsKey(culture))
{
result = values[culture];
}
return result;
}
set
{
string newVal = value;
if (values.ContainsKey(culture))
{
values[culture] = newVal;
}
else
{
values.Add(culture, newVal);
}
}
}
}

And it can be used in definitions like below:

public class City
{
int id;
LString name;
Lazy<Country> country;

public int ID
{
get { return id; }
set { id = value; }
}

public LString Name
{
get { return name; }
set { name = value; }
}

public Lazy<Country> Country
{
get { return country; }
set { country = value; }
}
}

So, an object of above defined class City will give you the string value of property Name like below:

City city = new City();
// Setter
city.Name[“en”] = “Name in English”;
city.Name[“ar”] = “Name in Arabic”;

// Getter
string cityName = city.Name[“en”];

Advertisements

About Saad Khan

Saad is an ASP.NET developer with 4 years of experience, and has also made a number of contributions to the Sitefinity marketplace and community. He loves to explore new code, and create innovative tools and procedures while exploring new approaches in his work with Sitefinity and MVC. As an experienced .NET developer, he frequents both Telerik and Microsoft technologies. In his spare time, Saad is an avid gamer and movie fanatic, and also experiments with new and interesting tools on the Microsoft platform.​​

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: