CodeConverter icon indicating copy to clipboard operation
CodeConverter copied to clipboard

VB -> C#: Switch on Object type results in behaviour change when cases are a different type

Open jconnop opened this issue 3 years ago • 1 comments

VB.Net input code

Public Class VisualBasicClass
    Sub Main()

        Dim StrObject As Object = "10"

        Select Case StrObject
            Case 10
                Console.WriteLine("Ten")
            Case 20
                Console.WriteLine("Twenty")
            Case Else
                Console.WriteLine("Else")
        End Select

        Console.ReadLine()

    End Sub
End Class

Output: Ten

Erroneous output

public partial class VisualBasicClass
{
    public void Main()
    {

        object StrObject = "10";

        switch (StrObject)
        {
            case 10:
                {
                    Console.WriteLine("Ten");
                    break;
                }
            case 20:
                {
                    Console.WriteLine("Twenty");
                    break;
                }

            default:
                {
                    Console.WriteLine("Else");
                    break;
                }
        }

        Console.ReadLine();

    }
}

Output: Else

Expected output

Looks pretty gross, but maybe something like this:

public partial class VisualBasicClass
{
    public void Main()
    {

        object StrObject = "10";

        switch (StrObject)
        {
            case var @case when Operators.ConditionalCompareObjectEqual(StrObject, 10, false):
                {
                    Console.WriteLine("Ten");
                    break;
                }
            case var @case when Operators.ConditionalCompareObjectEqual(StrObject, 20, false):
                {
                    Console.WriteLine("Twenty");
                    break;
                }

            default:
                {
                    Console.WriteLine("Else");
                    break;
                }
        }

        Console.ReadLine();

    }
}

Output: Ten

Details

  • Product in use: both
  • Version in use: VS Extension Version 9.0.4.0 / Website latest
  • Did you see it working in a previous version, which? No
  • Any other relevant information to the issue, or your interest in contributing a fix.

jconnop avatar Nov 02 '22 01:11 jconnop

Thanks for the great example. I think the solution is sensible, we just need to try to minimise the number of situations it happens in. E. G. Only when the (non converted) type of the label differs to the type of the switch variable.

GrahamTheCoder avatar Nov 02 '22 09:11 GrahamTheCoder