Previous | Index | Next 

[HOWTO] Transform “Not x Is y” expressions into “x IsNot y” expressions

NOTE: starting with build 1.00.05, VB Migration Partner automatically refactors expressions based on the “Is” operator and introduces the “IsNot” operator  if possible, therefore the technique described in this article is now obsolete. However, we haven’t withdrawn the article because it illustrates an advanced application of the PostProcess pragma.

VB.NET supports the IsNot operator, which permits to simplify expressions such as

        If Not x Is Nothing Then
            Do
                …
            Loop Until Not x Is Nothing
        End If

into a more readable:

        If x IsNot Nothing Then
            Do
                …
            Loop Until x IsNot Nothing
        End If

VB Migration Partner doesn’t automatically refactor expressions to leverage the IsNot operator, but you can easily reach the same effect by means of the following PostProcess pragma:

        '## PostProcess "\bNot\s+(?<par>\(\s*)?(?<obj>\S+)\s+Is\s+
            (?<value>\S+)\b(?(par)\))", "${obj}IsNot ${value}"

 

The above regular expression is a bit aggressive and might have one or more false matches, which in turn would generate statements that are invalid or that don’t behave as expected. If you realize that the pragma replace strings that it shouldn’t replace, you can try with the following, more granular pragmas:

        ' a pragma for simple If/ElseIf expressions
        '## PostProcess "(?<=[ \t]+)\b(?<keyword>ElseIf|If)\s+Not\s+(?<par>\(\s*)?
            (?<obj>\S+)\s+Is\s+(?<value>\S+)\s*(?(par)\))\s+Then\b",
            "${keyword} ${obj} IsNot ${value} Then"
        ' a pragma for Do/Loop expressions
        '## PostProcess "(?<=[ \t]+)\b(?<keyword>Do While|Do Until|Loop While|
            Loop Until)\s+Not\s+(?<par>\(\s*)?(?<obj>\S+)\s+Is\s+
            (?<value>\S+)\s*(?(par)\))(?=[ \t]*\r\n)", 
            "${keyword} ${obj} IsNot ${value}"
        ' a pragma for And/Or subexpressions
        '## PostProcess "\b(?<keyword>AndAlso|OrElse|And|Or)\s+Not\s+
            (?<par>\(\s*)?(?<obj>\S+)\s+Is\s+(?<value>\S+)(?(par)\))",
            "${keyword} ${obj} IsNot ${value}"

 

Previous | Index | Next