I have a class that contains another poco class with simple get set properties:
public class PersonalInformation {
public string FirstName { get; set; }
public string FirstSomethingElse { get; set; }
}
I would like to find out if the current instance’s PersonalInformation.FirstName has a value. I can’t figure out how to obtain it via reflection:
foreach (PropertyInfo property in this.PersonalInformation.GetType().GetProperties())
{
if (property.Name.Contains("First"))
{
if (property.GetValue(XXX, null) != null)
do something...
}
}
The instance I have is “this”, which does not work, neither does this.PersonalInformation. What am I doing wrong?
Thank you for your response,
Aldo
Addendum: I’m using ASP.NET MVC3. In my razor view I can do the following very easily:
foreach (var property in Model.PersonalInformation.GetType().GetProperties())
{
<div class="editor-line">
@if (property.Name != null)
{
<label>@(property.Name)</label>
@Html.Editor(property.Name)
}
</div>
}
there is a property.Value member that returns the current value of the field. This field comes from a poco class, as you see above. What would be the equivalent code in the code-behind?
this.PersonalInformationcertainly should work. After all, that’s the target you’re talking about.Sample code:
Although if you just “want to find out if the current instance’s PersonalInformation.FirstName has a value” then I don’t see why you’re using reflection…