Does VB.NET have pattern matching like C# does?

Viewed 342

Not too long ago C# added a nice "pattern matching" feature where you can check an object's type and cast it to that type all in one statement:

object o = GetSomeObjectFromTheDatabase();
if (o is Person p)
{
    Console.WriteLine($"{p.Name} is {p.Age} years old.");
}

Does VB.NET have anything like this, or will I have to do the type check and cast in two separate operations as I have in the past?

3 Answers

As I had previously noted in my own comment (and Codexer noted in the previous answer), this feature is not in VB.

Based on recent comments from Microsoft (https://devblogs.microsoft.com/vbteam/visual-basic-support-planned-for-net-5-0/) it doesn't seem likely that this feature will be added to the language in the near future. That having been said, the language still has a very full set of features that is missing very little for day-to-day development. If you're considering whether to do further development in VB, you would consider availability of development resources (internally and externally), suitability of VB for your project, and your current code base.

The .TryCast might be what you are looking for. If it succeeds, it will make the assignment, otherwise it returns Nothing. To test I just commented out one of the 2 Return statements. Note that the underlying type is Coffee if c is returned.

Private Function GetSomeObjectFromTheDatabase() As Object
    Dim dt = LoadCoffeeTable() 'Returns a DataTable
    Dim c = New Coffee(CInt(dt(0)(0)), dt(0)(1).ToString, dt(0)(2).ToString)
    'Return c
    Return "I am not a Coffee"
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim o As Object = GetSomeObjectFromTheDatabase()
    Dim p As Coffee = TryCast(o, Coffee)

    If p Is Nothing Then
        MessageBox.Show("Object is not a Coffee  " & o.ToString)
    Else
        MessageBox.Show(p.Name)
    End If
End Sub

Unfortunately VB doesn't have pattern matching as mentioned already in the comments. One option is to create a module so we can create an extension to use on anything we would need to type match.

Imports System.Runtime.CompilerServices

Module Extensions

    <Extension()>
    Public Function IsPatternMatch(Of T)(MyObj As Object, ByRef outObj As T) As Boolean
        Dim isMatch As Boolean = TypeOf MyObj Is T
        outObj = If(isMatch, CType(MyObj, T), outObj)
        Return isMatch
    End Function

End Module

Example Usage:

 Dim o As Object = Nothing
 Dim p As Person = Nothing

 o = GetSomeObjectFromTheDatabase()
 If o.IsPatternMatch(p) Then
    ' Do something with p now...
 End If
Related