Variable in a string

I need to get the value of a variable but the name is in a string

Page 1 of 1

3 Replies - 1173 Views - Last Post: 07 May 2008 - 04:37 AM Rate Topic: -----

#1 tecnipcs  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 05-May 08

Variable in a string

Post icon  Posted 05 May 2008 - 11:54 AM

I NEEED TO GET THE VALUE OF C USING USING X AS MY REFERENCE :blink:

string c = "11111";
string x = "c";
object s = x + ".Clone()";
Is This A Good Question/Topic? 0
  • +

Replies To: Variable in a string

#2 zakary  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 27
  • View blog
  • Posts: 427
  • Joined: 15-February 05

Re: Variable in a string

Posted 06 May 2008 - 05:30 AM

what is the problem here you already did what your asking

Quote

string x = "c";
just remove "" from c.

This post has been edited by zakary: 06 May 2008 - 05:31 AM

Was This Post Helpful? 0
  • +
  • -

#3 fikile82  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 07-May 08

Re: Variable in a string

Posted 07 May 2008 - 02:11 AM

View Posttecnipcs, on 5 May, 2008 - 11:54 AM, said:

I NEEED TO GET THE VALUE OF C USING USING X AS MY REFERENCE :blink:

string c = "11111";
string x = "c";
object s = x + ".Clone()";



Dude take a look

string c = "1111";

// this is how u get the value of c as ur ref

string x = c //Not "c" like in your case thats where u got everything wrong
Was This Post Helpful? 0
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon


Reputation: 6996
  • View blog
  • Posts: 14,635
  • Joined: 16-October 07

Re: Variable in a string

Posted 07 May 2008 - 04:37 AM

Trying to use eval in C#? Not without a lot of code, you essentially need a parser.

However, if you're simply trying to access a value indirectly, that you can do. However, that value must belong to an instance.

Here's an example:
using System;
using System.Diagnostics;
using System.Reflection;

class Program {
	public string c = "11111";
	static void Main(string[] args) {
		Program obj = new Program();
		string x="c";
		FieldInfo f = obj.GetType().GetField(x);
		object s = f.GetValue(obj);
		Debug.WriteLine(s);
	}
}



Hope this helps.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1