Note that there are some explanatory texts on larger screens.

plurals
  1. POMultidimensional dictionary with "add new value if key not in dictionary"
    primarykey
    data
    text
    <p>There were similar questions on SO, but none of them answered my question.</p> <p>I want to have two dimensional dictionary for translation. Something like this:</p> <pre><code>Dictionary["DE"][TranslationKeys.Title] = "Title in German"; Dictionary["DE"][TranslationKeys.SubTitle] = "Subtitle in German"; Dictionary["PL"][TranslationKeys.Title] = "Title in Polish"; Dictionary["PL"][TranslationKeys.SubTitle] = "Subtitle in Polish"; Dictionary["EN"][TranslationKeys.Title] = "Title in English"; Dictionary["EN"][TranslationKeys.SubTitle] = "Subtitle in English"; </code></pre> <p>which is OK if i use traditional dictionary like <code>Dictionary&lt;string,Dictionary&lt;TranslationKeys,string&gt;&gt;</code></p> <p>But i <strong>don't</strong> want to initialize it in "ugly" way like this:</p> <pre><code>Dictionary = new Dictionary&lt;string,Dictionary&lt;TranslationKeys,string&gt;&gt;(){ {"PL",new Dictionary&lt;TranslationKeys,string&gt;(){{TranslationKeys.SubTitle,"Subtitle in Polish"}}} }; </code></pre> <p>but like this:</p> <pre><code>Dictionary["PL"][TranslationKeys.SubTitle] = "Subtitle in Polish"; </code></pre> <p>So I've tried to implement an "intelligent" multidimensional dictionary that would figure out itself if he got the value or not. What I've done this far is a new generic class that uses Dictionary and special indexer:</p> <pre><code>public class TranslateDictionary&lt;TKey, TValue&gt; where TValue : new() { private Dictionary&lt;TKey, TValue&gt; Dictionary; public TValue this[TKey lang] { get { if (!Dictionary.ContainsKey(lang)) { TValue obj = new TValue(); Dictionary.Add(lang, new TValue()); } return Dictionary[lang]; } set { Dictionary[lang] = value; } } } </code></pre> <p>But now i'm stuck... Because i'm using strings in my generic typed TranslateDictionary i'm gettint this error:</p> <blockquote> <p>Error 2 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TValue' in the generic type or method 'Resources.TranslateDictionary' </p> </blockquote> <p>Allthough compiler doesn't complain about initialization like this:</p> <pre><code>Dictionary["EN"][TranslationKeys.Title] = "Title in English"; </code></pre> <p>Maybe i should use other type of collection instead of Dictionary that i'm not aware of, to solve my problem? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload