user1524116
user1524116

Reputation: 75

Use contents of a string as a statement

I would like to use the contents of a string as a statement, for example:

string exampleString = "exampleStatement";
exampleString.exampleMethod();

The use of it in my actual program is below

XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();

string field = "PublishDate";


foreach (SyndicationItem item in feed.Items)
{
    data = item.field.ToString();
}

 return data;

Is this possible to do?

Upvotes: 0

Views: 88

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062755

This is not trivial like it might be, say, in ecmascript. The simplest option is reflection, for example:

data = item.GetType().GetProperty(field).GetValue(item).ToString();

however: depending on the API involved, there may be other options available involving indexers, etc. Note that reflection is slower than regular member access - if you are doing this in very high usage, you might need a more optimized implementation. It (reflection) is usually fast enough for light to moderate usage, though.

Upvotes: 1

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

You can use reflection

item.GetType().GetProperty(field).GetValue(item).ToString();

(or GetField() instead of GetProperty() if... that's a field)

Upvotes: 2

Related Questions