1

I am not a .net developer, and I need to assign 35 values to the inputs of a external method using .net 3.5. The method inputs look something like this:

proc.x1 = "ABC"
proc.x2 = "DEF"
...
proc.x35 = "ZZZ"

I'm getting the values I need to assign by parsing a delimited string into a dictionary, with the ordinal position of each substring as my key value.

string proccode = "9052   9|9605   9|966    9|9607   9|4311   9";
foreach (string xProc in proccode.Split('|'))
{ 
    procs.Add(iProc, xProc.Substring(0, 7) + "Y");    
    Console.WriteLine(aProc + " " + iProc);
    aProc = aProc + xProc.Substring(0, 7);
    iProc = iProc + 1;
}

1 or all of the key values may not exist. (the entire string can be null; the above example only has 5).

I'm currently using the code below 35 times to assign the values to the variables (which I learned here):

if(diags.TryGetValue(1, out value))
{
    proc.x1=diags[1];
}

But repeating this code 35 times seems like poor design.

Once I've assigned all of the inputs, the external code does something in a black box:

proc.Calc()

It returns a bunch of unrelated values (correctly).

Is there a superior way to accomplish this?

Community
  • 1
  • 1
Eric Hauenstein
  • 2,557
  • 6
  • 31
  • 41

2 Answers2

2

You can use reflection in order to set x1..x35 properties (or fields) in a single loop:

  Dictionary<int, String> diags = ...;

  Type tp = proc.GetType();

  foreach (var pair in diags) {
    // if p1..p30 are fields use FieldInfo instead of PropertyInfo
    // FieldInfo pi = tp.GetField("x" + pair.Key.ToString());
    PropertyInfo pi = tp.GetProperty("x" + pair.Key.ToString());

    if (!Object.ReferenceEquals(null, pi))
      pi.SetValue(proc, pair.Value);
  }

  proc.Calc();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
2

You could use reflection to set the values. Example:

void Main()
{
    var dic = new Dictionary<int, string>()
    { 
        { 1, "Arne" },
        { 2, "Kalle" }
    };

    var t = new Test();
    var props = typeof(Test).GetProperties(BindingFlags.Instance | BindingFlags.Public);
    foreach (var p in props)
    {
        var key = int.Parse(p.Name.Substring(1));
        string value;
        if(dic.TryGetValue(key, out value))
        {
            p.SetValue(t, value);
        }
    }
}

public class Test
{
    public string x1 { get; set; }
    public string x2 { get; set; }
}
Magnus
  • 45,362
  • 8
  • 80
  • 118