1

I want to use a string as part of a variable.

For example in the code below I have a String called productLine. I want to use the value in this string to create a variable name and to call to the property "Value" on this variable. I want to keep switching the value in 'productLine', and therefore keep switching the variable who's value method is called.

Is there a way to do this or will I need to rewrite the code and take a different approach?

foreach (string productLine in productLineData)
{
    string templateKey = "{{" + productLine + "}}";
    string templateValue = "";
    if (productRow.productLine.Value != null)
        templateValue = productRow.productLine.Value.ToString();
    productRowText = productRowText.Replace(templateKey, templateValue);
}

productRow is a model which contains the properties I wish to use.

EDIT:

productLine contains a String value. For example it contains productName at first. At that point I want to call productRow.productName.Value. Next 'productLine' contains productPrice. At that point I want to call productRow.productPrice.Value. etc.

MeRgZaA
  • 25
  • 7
  • 4
    The question is currently quite confusing(probably just a language issue). You want to use a string as part of a variable? You have `productLine` which is filled with a string? You want to keep switching between from where value is called? You need to explain it in other words or with examples. – Tim Schmelter May 19 '16 at 13:44
  • It might just be my lack of understanding, but i do not really see how that other question is the answer to my problem. – MeRgZaA May 19 '16 at 13:56

2 Answers2

3

You can do that using reflection as romain-aga suggested.

 using System.Reflection;


    //...
    foreach (string productLine in productLineData)
    {
        string templateKey = "{{" + productLine + "}}";
        string templateValue = string.Empty;
        object value =  productRow?.GetType()?.GetProperty(productLine)?.GetValue(productRow, null);
        if (value != null)
            templateValue = value.ToString();
        productRowText = productRowText.Replace(templateKey, templateValue);
    }
    //...
  • 1
    Good answer. I would have just added a test to check if `productRow.GetType().GetProperty(productLine)` is not null before calling `GetValue`:-) – aprovent May 19 '16 at 14:20
  • 1
    You are right. See edit using new language feature. –  May 19 '16 at 14:23
0

If the variable you want to address is a property of a class (i.e. a member) then Reflection will allow you to get/set its value by using the string of its name. If the variable is just a function scoped symbol (i.e. string myVar = ""; ) then it doesn't exist at runtime and cannot be accessed.

PhillipH
  • 6,182
  • 1
  • 15
  • 25