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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With