3

I am pulling several elements of data out of an object in C#. They are all in the same 'place' within the object, as in:

objectContainer.TableData.Street.ToString());
objectContainer.TableData.City.ToString());
objectContainer.TableData.State.ToString());
objectContainer.TableData.ZipCode.ToString());

I would LIKE to use a foreach loop to pull them all and be able to add more by adding to the array.

string[] addressFields = new string[] { "Street", "City", "State", "ZipCode" };
foreach(string add in addressFields) 
{
  objectContainer.TableData.{add}.ToString());
}  

Can this be done, and if so, what is the correct procedure?

3
  • what is TableData ?? What type is it? Commented Jan 25, 2013 at 13:18
  • Are you trying to add items to your TableData, or you want to get items from TableData? Your intent is not clear Commented Jan 25, 2013 at 13:18
  • I am trying to Get and yes, the GetType().GetProperty() is what I was looking for and couldn't find. Thank you all. Commented Jan 25, 2013 at 14:31

2 Answers 2

3

You would need to use reflection to achieve this:

var type = objectContainer.TableData.GetType();

foreach(var addressFieldName in addressFieldNames)
{
    var property = type.GetProperty(addressFieldName);
    if(property == null)
        continue;
    var value = property.GetValue(objectContainer.TableData, null);
    var stringValue = string.Empty;
    if(value != null)
        stringValue = value.ToString();
}

Please note: This code is pretty defensive:

  • It will not crash if no property with the specified name exists.
  • It will not crash if the value of the property is null.
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Reflection to do this.

string[] addressFields = new string[] { "Street", "City", "State", "ZipCode" };
foreach(string add in addressFields) 
{
  var myVal = objectContainer.TableData.GetType().GetProperty(add).GetValue(objectContainer.TableData).ToString();
}

Note that this doesn't allow for array values that don't have a corresponding property on objectContainer.TableData.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.