Search code examples
c#object-property

Eliminating Multiple If Statements For Pulling A Specific Object Property


Model:

public class ServiceHours
{
    public int Id { get; set; }
    ...
    public TimeSpan? Monday { get; set; }
    public TimeSpan? Tuesday { get; set; }
    public TimeSpan? Wednesday { get; set; }
    public TimeSpan? Thursday { get; set; }
    public TimeSpan? Friday { get; set; }
    public TimeSpan? Saturday { get; set; }
    public TimeSpan? Sunday { get; set; }
}

I'm currently iterating through a list of "service hour" objects (they can hold an optional start time for 1 or multiple days of the week). I want to be able to dynamically grab the value that corresponds to the DayOfWeek enum from a DateTime object.

This works but isn't very elegant

var today = DateTime.Today.DayOfWeek;

foreach (var item in myItems)
{
    var time = new TimeSpan?();

    if (today == DayOfWeek.Monday)
        time = item.Monday;
    else if (today == DayOfWeek.Tuesday)
        time = item.Tuesday;
    else if (today == DayOfWeek.Wednesday)
        time = item.Wednesday;
    else if (today == DayOfWeek.Thursday)
        time = item.Thursday;
    else if (today == DayOfWeek.Friday)
        time = item.Friday;
    else if (today == DayOfWeek.Saturday)
        time = item.Saturday;
    else if (today == DayOfWeek.Sunday)
        time = item.Sunday;

    ...
}

UPDATE: I ended up using reflection at the time, but this was a very poor, naive design to begin with and this question should've been posted to Code Review anyways - This question should be disregarded, just adding this notice in case any others come along. Thanks to those who attempted to help out regardless of the terrible question!


Solution

  • Something like this probably (did not compiled this code though)

    object.GetType().GetProperty(today.DayOfWeek.ToSring()).GetValue(object)
    

    use reflection to get property value,with only condition that DayOfWeek enum member has to have exact name of the property present in object type.