Loop through an object's properties and get the values for those of type DateTime

C#.NetReflection

C# Problem Overview


I have a list of objects (Cars). For each car in the list I need to loop through it and find any properties of type DateTime. If I find a property of DateTime I need to get the value and do a time conversion. For now lets just print out the DateTime property value to the console. I am having issues understanding what I need to put in the first parameter of the prop.GetValue function. Any help would be appreciated!

foreach (var car in carList)
{  
    foreach (PropertyInfo car in car.GetType().GetProperties())
    {
        var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
        if (type == typeof (DateTime))
        { 
            Console.WriteLine(prop.GetValue(???, null).ToString());
        }
    }
}

C# Solutions


Solution 1 - C#

You need to use car as the first parameter:

foreach (var car in carList)
{  
    foreach (PropertyInfo prop in car.GetType().GetProperties())
    {
         var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
         if (type == typeof (DateTime))
         { 
             Console.WriteLine(prop.GetValue(car, null).ToString());
         }
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSealer_05View Question on Stackoverflow
Solution 1 - C#aybeView Answer on Stackoverflow