3

I have to implement a solution something like - my c# function I use so many harcoded five digits codes. what I want to so is to move these hard coded values into a mapping config file(some xml) and The config will map the codes to constants that can be used in my function.

This will help to update the code value without source code re-compilation.

XML would be like:

<Codes>
    <Code>
        <key>code_name_1</key>
        <value>value_1</value>
    </Code>
    ...
</Codes>

OR

 <Codes>
    <Code key='code_name_1' value='value_1'>
    <Code key='code_name_2' value='value_2'>
    <Code key='code_name_3' value='value_3'>
    ...
</Codes>

mapping class would be:

static class codeMapping
{
const sting code1 = "code_name_1";
const sting code2 = "code_name_2";
const sting code3 = "code_name_3";
const sting code4 = "code_name_4";
...
}

function where I want to get these values:

class someClass
{
 ...someFunction(string someCode)
    {
    ...
    if(someCode == codeMapping.code1)
    ...do something

    var temp2 = codeMapping.code2;
    ...
    }
}

How to initialize constant variables of codeMapping class to the corresponding config valies? Any better design concept is also accepted.

nectar
  • 9,525
  • 36
  • 78
  • 100
  • You've made this question unnecessarily confusing; please show us your actual XML instead of variations on what it is “something like”. For example you say you use “five digits codes” yet none of your examples show this; the rules for XML elements and attributes are different but you give no indication which rules your codes should follow. When you talk about your “config” do you mean a Visual Studio .config file? An app.config? Something you made up? Why are you going through this “mapping” at all? You can load, save, and parse XML data directly without going through any “mapping”. – Dour High Arch Aug 08 '14 at 21:05

1 Answers1

0

Use static readonly fields instead and initialize it inside constructor. Hope this is what you are trying to achieve.

class Program
    {
        static void Main(string[] args)
        {
            var s = CodeMapping.Code1;
        }

        public static class CodeMapping
        {
            private static readonly string _code1;
            private static readonly string _code2;

             static CodeMapping()
             {
                 string filePath = "code file path";
                 var doc = XElement.Load(filePath);
                 _code1 = doc.Elements().SingleOrDefault(r => r.Element("key").Value == "code_name_1").Element("value").Value;
                 _code2 = doc.Elements().SingleOrDefault(r => r.Element("key").Value == "code_name_2").Element("value").Value;
             }

             public static string Code1 { get { return _code1; }}
             public static string Code2 { get { return _code2; } }
        }
    }

Static readonly vs const

Community
  • 1
  • 1
AllSpark
  • 425
  • 1
  • 4
  • 17