Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading