Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a simple name value mapper class in C#

Tags:

c#

I want to create a class (static?) that simply maps a name to a value (1 to 1). What's a clean way of doing something like this:

public static class FieldMapper
{
  public static GetValue(string Name)
  {
    if (Name == "abc")
        return "Value1";

    if (Name == "def")
        return "Value2";
  }
}

I might be having a mind block today. I am unable to think of a clean solution for a simple problem like this :(

Edit: All the values are known at compile time (There is no uniqueness - different keys can map to same value). I shouldn't be creating a datastructure that adds values at runtime. Also, I would like to avoid using a XML file

like image 718
DotnetDude Avatar asked Jul 14 '26 15:07

DotnetDude


1 Answers

Sounds like a job for a dictionary.

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("abc", "Value1");
values.Add("def", "Value2");
Console.WriteLine(values["abc"]);   // Prints "Value1"