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?

2 Answers2

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.
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
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.

squillman
  • 13,363
  • 3
  • 41
  • 60