0

Writing a C# Azure function and trying to use C#8 switch expressions.

Accoring to the docs, https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.switchexpressionexception?view=netcore-3.1, they show this should be available for .net core 3.1

This code, that uses the switch expression does not work:

try
{
    var data = (JObject)eventGridEvent.Data;
    IDHT22 sensor = eventGridEvent.EventType switch
    {
        "TemperatureChangedEvent" => new TemperatureSensorEvent(data["sensor_id"].Value<string>(), data["name"].Value<string>(), data["temperature_c"].Value<double>()),
        "HumidityChangedEvent" => new HumiditySensorEvent(data["sensor_id"].Value<string>(), data["name"].Value<string>(), data["humidity"].Value<double>())
    };

    if (sensor != null)
        await sensors.AddAsync(sensor);

}
catch (System.Exception ex)
{
    throw new InvalidOperationException(ex.Message, ex);
}

When executed it results in this error message:

[4/30/2020 7:21:06 PM] Executed 'SaveSensorEvent' (Failed, Id=8db720e1-aa19-4f53-b102-3aaa83f19667) [4/30/2020 7:21:06 PM] System.Private.CoreLib: Exception while executing function: SaveSensorEvent. > SensorData: Could not load type 'System.Runtime.CompilerServices.SwitchExpressionException' from assembly 'System.Runtime.Extensions, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

If i use a traditional switch it's all good. Seems i might need to update the Runtime.Extensions perhaps - though unsure how to do this in a .net core app.

Any ideas?

Darren Wainwright
  • 30,247
  • 21
  • 76
  • 127

1 Answers1

0

Apparently, you're missing the default case in your code.

It should look like this:

IDHT22 sensor = eventGridEvent.EventType switch
{
    "TemperatureChangedEvent" => new TemperatureSensorEvent(data["sensor_id"].Value<string>(), data["name"].Value<string>(), data["temperature_c"].Value<double>()),
    "HumidityChangedEvent" => new HumiditySensorEvent(data["sensor_id"].Value<string>(), data["name"].Value<string>(), data["humidity"].Value<double>()),
    _     => balabala
};
Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60