Question

I am using Visual Studio 2013 and C#

I want to be able to compare the name of a string variable with a string I create.

The string variable is called print1 (for instance)

public string print1;

I then create a string to like so:

foreach (int number in orderOfNumber)
{
    string printNumber = String.Format("print{0}", number-1);
}

I discard this if 'number' = 1 so I am not concerned with the number ever being 0

What I would like to do is print a string in a MessageBox with a few lines. One line will have the time taken between clicking two pictures on the screen. Basically formatted like this:

//Time taken:

1 and 2 -> 1.234 secs

What I have so far is this:

orderBuilder.Append(String.Format("{0} and {1}\t\t", orderOfNumber[number-1], orderOfPicturesNumber[number])).Append("" + printNumber + "\n");

No matter how I try I always end up with

1 and 2 print1

This is close to what I want as the value for print1 is actually 1.234

Is there a way to replace the 'string' print1 with the original variable print1?

Was it helpful?

Solution

I would create an array of values:

public string[] prints;

You'll, of course, have to initialize it with the number of values you want to hold:

prints = new string[5]; // Holds five strings

Then, you can loop through them as such:

foreach (var number in prints) // Loop through each string in prints
{
    string printNumber = String.Format("print{0}", number);
}

If you want to be able to dynamically add or remove strings for prints, you should probably use a List<string> instead of a string[]

OTHER TIPS

Try using this code:

PropertyInfo pi = this.GetType().GetProperty(printNumber);
string value = (string)(pi.GetValue(null, null));

Only thing you must do is to declare your variables as properties.

Source: http://www.karpach.com/Reflection-Property-Value.htm

-- EDIT --

I found a method I didn't know about... GetField which can return field values so that you don't need to declare your variables as properties, you can use them directly.

public class SomeClass
{
    public int a0 = 1;
    public int a1 = 2;
    public int a2 = 3;

    public void DoSomething()
    {
        int result = 1;

        for (int index = 0; index < 3; index++)
        {
            string fieldName = "a" + index;

            var field = typeof(SomeClass).GetField(fieldName);
            int fieldValue = (int)field.GetValue(this);

            result *= fieldValue;
        }

        Debug.Assert(result == 6);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top