Using a variable inside an object member
I am retrieving multiple data items from an object in C #. They are all in the same place in the object, for example:
objectContainer.TableData.Street.ToString());
objectContainer.TableData.City.ToString());
objectContainer.TableData.State.ToString());
objectContainer.TableData.ZipCode.ToString());
I'd like to use a foreach loop to pull them all out 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
source to share
2 answers
To achieve this you need to use reflection:
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 secure:
- It will not fail if no property with the specified name is found.
- It won't fire if the property value is
null
.
+3
source to share
You can use Reflection for 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 does not allow array values ββthat do not have a corresponding property in theContainer.TableData object.
0
source to share