If I have an object which has other nested objects and properties, like the one below.
var request = new GetInfoRequest
{
GetInformation = new GetInformationType
{
Code = "abc",
Id = "123",
Item = new InfoItem
{
Itemid = "test",
ItemName = "testname"
},
StartDate = new StartdatumType { Start = new DateTime(1990, 1, 1)},
EndDate = new EndDateType { End = new DateTime.Now }
}
};
When passing this object to a function I want to check that none of its properties or objects are null
.
public InfoResponse getInfo(request)
{
// Check that the request object has no null properties or objects.
}
Is there a simpler way of checking this than stepping through each child object and property with if statements? A recursive method or something similar?
Extending
In my getInfo function I don't want to have to write like this:
if (request != null && request.GetInformation != null && ... etc.)
Use reflection and iterate through all the properties to check for null. Here is a snippet to get started
using System.Reflection;
GetInfoRequest objGetInfoRequest;
Type getInfoRequestType = objGetInfoRequest.GetType();
PropertyInfo[] myProps = getInfoRequestType.GetProperties();
you could use reflection to iterate through the fields.
you well need some recursion for the nested values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.