expression evaluation

G

Guest

If I have a string variable that contains the name of a property, how can I
evaluate that string in code to be used as a property?

For example:

public struct myData
{
public string first_item;
public string next_item;
}

myData x;
string myItem = "first_item";

x.myItem <----- This is where I want the myItem evaluated so it understands
this is a property of x.

Thanks!
 
J

Jon Shemitz

David said:
If I have a string variable that contains the name of a property, how can I
evaluate that string in code to be used as a property?

For example:

public struct myData
{
public string first_item;
public string next_item;
}

myData x;
string myItem = "first_item";

x.myItem <----- This is where I want the myItem evaluated so it understands
this is a property of x.

Reflection. typeof(myData).GetProperty(myItem)
 
R

realfun

I wonder why you need this, perhaps there is another way with no
performace penalty.

if you need, use Reflection, example:
//-------------------------------------
public static void Main()
{
myData x;
x.first_item = "{test first_item}";
x.next_item = "{test next_item}";

string myItem = "first_item";

FieldInfo myFieldInfo;
Type myType = typeof(myData);
// Get the type and fields of FieldInfoClass.
myFieldInfo = myType.GetField(myItem);
Console.WriteLine(myFieldInfo.FieldType.ToString());
Console.WriteLine(myFieldInfo.Name.ToString());
Console.WriteLine(myFieldInfo.GetValue(x).ToString());
}

public struct myData
{
public string first_item;
public string next_item;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top