-2

Consider:

int x = 10;

and String str = "x";.

I want to output 10 by calling the str variable as it has value x. But the problem is it is a string x with "" to be called in:

response.write();

How can I fix this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    unable to understand !,rephrase ur statements – Ashok Damani May 25 '13 at 07:26
  • Depending on how and where you declare `x`, maybe you can use reflection. But maybe just using a `Dictionary` will suffice for what you're trying to do. – Corak May 25 '13 at 07:26
  • A string is a string. A variable is a variable. You do not cast a variable to a String by surrounding it in quotes. Try String str = x.ToString(); See http://stackoverflow.com/questions/3081916/convert-int-to-string-in-c-sharp – BLaZuRE May 25 '13 at 07:27

2 Answers2

0

You can wrap it in a container.. something like this:

class Container {
    public int X { get; set; }

    public Container() {
        X = 10;
    }
}

// .. elsewhere...

object getVariableValueByStringName(string str) {
    return typeof(Container).GetProperty(str).GetValue(new Container() /* <-- dummy or not.. up to you -->);
}
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
0

I think you need to output the value of x i.e. 10 in response.write(). You can even do that without the String variable str, like:

response.write(x);

or response.write(x.ToString());

And as per your code

int x = 10;
and

String str = x.ToString();

instead of String str = "x".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Parth mehta
  • 1,468
  • 2
  • 23
  • 33