Search code examples
c#switch-statement.net-4.5c#-5.0c#-8.0

How to convert a C#8 switch expression to a classic switch?


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;
    }

Solution

  • The idea behind it is almost the same as what you have written. Here is the syntax for C# 7:

    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;
    }
    

    The above solution needs C# 7 to work. If you are using a language version below that, you have to content yourself with simple if statements.

    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;
    }