Reputation: 555
I have a method parameter of type Object response. I'm iterating through the object using:
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(response))
{
string name = descriptor.Name;
object value = descriptor.GetValue(response);
Console.WriteLine("{0}={1}", name, value);
if (name.Contains("StatusData"))
{
//loop thorugh StatusDataReponse properties
}
When the object contains a property of StatusData, I need to convert it to StatusDataResponse and loop through it's properties. I'm coming from vb.net and not sure how to do this in c#.
Upvotes: 0
Views: 134
Reputation: 12944
If I were you, I would not check on the name, but just check on the type. This way you are safe for:
StatusData
but which is of type StatusDataReponse
.StatusData
but which are NOT of type StatusDataReponse
.Exaple:
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(response))
{
string name = descriptor.Name;
object value = descriptor.GetValue(response);
StatusDataReponse statusData = value as StatusDataReponse;
if (statusData == null)
{
Console.WriteLine("{0}={1}", name, value);
}
else
{
//loop thorugh StatusDataReponse properties
}
Upvotes: 0
Reputation: 7692
To be really straightforward:
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(response))
{
string name = descriptor.Name;
object value = descriptor.GetValue(response);
Console.WriteLine("{0}={1}", name, value);
if (name.Contains("StatusData"))
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(value))
{
...
}
}
}
Upvotes: 0
Reputation: 4544
you read about covariance and contravariance in c# .Try to use this.I think it will work if value is inherited property.If I am wrong please comment.
if (name.Contains("StatusData"))
{
//loop thorugh StatusDataReponse properties
StatusDataReponse response = (StatusDataReponse)value;
if (response != null)
{
// Use response as needed
}
}
Upvotes: 1
Reputation: 564333
Since you know the type, you can convert the value directly:
if (name.Contains("StatusData"))
{
//loop thorugh StatusDataReponse properties
StatusDataReponse response = value as StatusDataReponse;
if (response != null)
{
// Use response as needed
}
}
Upvotes: 4