Question:
Good morning SOes brothers, I have this situation:
I need a dictionary with previously defined data, this dictionary is supposed to be read-only so the million dollar question is:
How can I define a static dictionary with initialized elements?
This way when you have to work some clave
, the valor
will be obtained from the dictionary.
Answer:
If the data in that dictionary is readonly and it is a dictionary for the entire class, make static
and of type readonly
public class ClaseDeEjemplo {
public static readonly Dictionary<string, string> ejemploDiccionario = new Dictionary<string, string>() {
{"Clave1", "Valor1"},
{"Clave2", "Valor2"},
{"Clave3", "Valor3"}
};
}
And you use it as follows:
var ValorDependiendoDeLaClave = ejemploDiccionario[VariableDeNombreDeAlgunaClave];
That is, if VariableDeNombreDeAlgunaClave
contains a string named Clave1
, the value will be Valor1
.