简体   繁体   中英

C# What's the difference between using these two switch operations?

I know two ways with switch statement to write logic what I want to implement in C#. They are:

int hour = DateTime.Now.Hour;
string timeWord = string.Empty;

// first
switch (hour)
{
    case int x when hour < 12:
        timeWord = "morning";
        break;
    case int x when hour < 18:
        timeWord = "afternoon";
        break;
    case int x when hour < 24:
        timeWord = "evening";
        break;
    default:
        throw new Exception("Another fine mess you got us into");
}
// second
switch (hour)
{
    case < 12:
        timeWord = "morning";
        break;
    case < 18:
        timeWord = "afternoon";
        break;
    case < 24:
        timeWord = "evening";
        break;
    default:
        throw new Exception("Another fine mess you got us into");
}

These variants work identically and I know they represent relational pattern. But is there a difference which variant will I use in my program?

The second way will be optimized to do binary search but the first way not (in the current version of compiler).

It is not so important for switch with three cases, but may improve performance for large switch .

The second way is equivalent of something like this, which in the worst case results in two comparisons, in general has O(log(casesCount)) complexity:

if (hour < 18)
  timeWord = hour < 12 ? "morning" : "afternoon";
else if (hour < 24)
  timeWord = "evening";
else
  throw ...;

The first way checks all conditions sequentially, which in the worst case results in three comparisons, and has linear complexity:

if (hour < 12)
  timeWord = "morning";
if (hour < 18)
  timeWord = "afternoon";
if (hour < 24)
  timeWord = "evening";
else
  throw ...;

But a much better way to write this switch is to use switch expression rather than statement , much shorter and compiles like the second way:

var timeWord = hour switch {
  < 12 => "morning",
  < 18 => "afternoon",
  < 24 => "evening",
  _ => throw new Exception()
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM