patterncsharpMinor
A switch case statement that returns a timespan
Viewed 0 times
casestatementthatreturnstimespanswitch
Problem
I have a switch case statement containing enum values as cases. These enum values are time units. Now I want to generate a timespan by using an enum value and a long value so like this:
2 (long) Minutes (Enum value)
1 (long) Year (Enum value)
... and so on.
This is the switch-case statement:
But I don't like it and it feels very double. Could anyone review this and refactor it, since I'm not able to see it.
2 (long) Minutes (Enum value)
1 (long) Year (Enum value)
... and so on.
This is the switch-case statement:
private const double yearValue = 365.2425;
public TimeSpan ResetTimeSpan
{
get
{
switch (ResetTimeUnitEnumValue)
{
case TimeUnit.Seconds:
return new TimeSpan(0,0,0, (int)ResetTime);
case TimeUnit.Minutes:
return new TimeSpan(0, 0, (int)ResetTime, 0);
case TimeUnit.Hours:
return new TimeSpan(0, (int)ResetTime, 0);
case TimeUnit.Days:
return new TimeSpan((int)ResetTime, 0, 0, 0);
case TimeUnit.Months:
return new TimeSpan((int)(ResetTime * (yearValue / 12)), 0, 0, 0);
case TimeUnit.Years:
return new TimeSpan((int)(ResetTime * yearValue), 0, 0, 0);
default:
throw new ArgumentOutOfRangeException();
}
}
}But I don't like it and it feels very double. Could anyone review this and refactor it, since I'm not able to see it.
Solution
private const double yearMultiplier = 365.2425;
private Dictionary> timespanConverters = new Dictionary>
{
{ TimeUnit.Seconds, TimeSpan.FromSeconds },
{ TimeUnit.Minutes, TimeSpan.FromMinutes },
{ TimeUnit.Hours, TimeSpan.FromHours },
{ TimeUnit.Days, TimeSpan.FromDays },
{ TimeUnit.Months, t => TimeSpan.FromDays((int)t * (yearMultiplier / 12))) },
{ TimeUnit.Years, t => TimeSpan.FromDays((int)t * yearMultiplier)) }
}
// ....
public TimeSpan ResetTimeSpan
{
get
{
return timespanConverters[ResetTimeUnitEnumValue](ResetTime);
}
}Bit of a shame that
System.TimeSpan doesn't have FromMonths or FromYears methods otherwise this would look really neat :)Code Snippets
private const double yearMultiplier = 365.2425;
private Dictionary<TimeUnit, Func<double, TimeSpan>> timespanConverters = new Dictionary<TimeUnit, Func<double, TimeSpan>>
{
{ TimeUnit.Seconds, TimeSpan.FromSeconds },
{ TimeUnit.Minutes, TimeSpan.FromMinutes },
{ TimeUnit.Hours, TimeSpan.FromHours },
{ TimeUnit.Days, TimeSpan.FromDays },
{ TimeUnit.Months, t => TimeSpan.FromDays((int)t * (yearMultiplier / 12))) },
{ TimeUnit.Years, t => TimeSpan.FromDays((int)t * yearMultiplier)) }
}
// ....
public TimeSpan ResetTimeSpan
{
get
{
return timespanConverters[ResetTimeUnitEnumValue](ResetTime);
}
}Context
StackExchange Code Review Q#27552, answer score: 7
Revisions (0)
No revisions yet.