Home > Mobile >  How to convert a C#8 switch expression to a classic switch?
How to convert a C#8 switch expression to a classic switch?

Time:09-02

Could anyone help me to convert the below expression to a classic switch since i can't use it?

private static bool TryGetScaleTransform(FrameworkElement frameworkElement, out ScaleTransform scaleTransform)
    {
        scaleTransform = frameworkElement.LayoutTransform switch
        {
            TransformGroup transformGroup => transformGroup.Children.OfType<ScaleTransform>().FirstOrDefault(),
            ScaleTransform transform => transform,
            _ => null
        };

        return scaleTransform != null;
    }

CodePudding user response:

The idea behind it is almost the same as what you have written. Here is the syntax:

private static bool TryGetScaleTransform(FrameworkElement frameworkElement, out ScaleTransform scaleTransform)
{
    switch(frameworkElement.LayoutTransform)
    {
        case TransformGroup transformGroup:
            scaleTransform= transformGroup.Children
                .OfType<ScaleTransform>().FirstOrDefault();
            break;
        case ScaleTransform transform:
            scaleTransform = transform;
            break;
        default:
            scaleTransform = null;
            break;
    }

    return scaleTransform != null;
}

Edit: This solution needs C# 7 to work. If you are using a language version below that, you have to contend yourself with if - else.

private static bool TryGetScaleTransform(FrameworkElement frameworkElement, out ScaleTransform scaleTransform)
{
    if(frameworkElement.LayoutTransform is TransformGroup)
    {
        scaleTransform = frameworkElement.LayoutTransform.Children
            .OfType<ScaleTransform>().FirstOrDefault();
        return true;
    }

    if(frameworkElement.LayoutTransform is ScaleTransform)
    {
         scaleTransform = frameworkElement.LayoutTransform;
         return true;
    }

    scaleTransform null;
    return false;
}
  • Related