20

Is there a VB.NET equivalent to the C# 7 is operator declaration pattern? Note in particular the bmp in the following code sample:

public void MyMethod(Object obj)
{
    if (obj is Bitmap bmp)
    {
        // ...
    }
}

Or the short pattern matching syntax with is is exclusive to C#?

EDIT:

I already know these syntaxes:

    If TypeOf obj Is Bitmap Then
        Dim bmp As Bitmap = obj
        ' ...
    End If

or

    Dim bmp As Bitmap = TryCast(obj, Bitmap)
    If bmp IsNot Nothing Then
        ' ...
    End If

What I want to know is whether there is something even shorter, like that new C#7 is operator declaration pattern...

Thank you very much.

Gary Barrett
  • 1,764
  • 5
  • 21
  • 33
VBobCat
  • 2,527
  • 4
  • 29
  • 56
  • 2
    Sorry, I didn't asked clearly from begginning. Please see edit. – VBobCat Nov 26 '17 at 11:23
  • 3
    I think there is no. The team of vb.net [chose not to run after the incessant improvements of C#](https://blogs.msdn.microsoft.com/vbteam/2017/02/01/digging-deeper-into-the-visual-basic-language-strategy/). – dovid Nov 26 '17 at 11:49
  • 3
    https://github.com/dotnet/vblang/issues/124 https://github.com/dotnet/vblang/issues/172 – dovid Nov 26 '17 at 12:05
  • This trick isn't the cast. The trick is the variable declaration in the same line of code. – Joel Coehoorn Feb 15 '18 at 05:11
  • There are now a few related open proposals on the vblang Github repo; see [here](https://github.com/dotnet/vblang/issues/337) and [here](https://github.com/dotnet/vblang/issues/367) among others. – Zev Spitz Dec 13 '19 at 08:00

2 Answers2

3

Currently, no. If you want to implement this, you'll have to use some of the longer formats you already mention in your question.

The C# and VB languages don't always have equivalent features.

simonalexander2005
  • 4,338
  • 4
  • 48
  • 92
-1

Use a one line if

If obj is bitmap Then Dim bmp = obj

or use an in-line if (this is the if function)

Dim bmp = If(obj is bitmap, obj, Nothing)

Not quite pattern-matching per se, but is does the same thing.

Couldn't you do it this way in C#:

var bmp = obj is bitmap ? obj : nothing;
John Grabauskas
  • 310
  • 2
  • 5
  • 2
    As far as my testing goes, this would miss object typing and return Object type. – bkqc Dec 17 '20 at 19:07
  • `obj is bitmap` is illegal. – NetMage May 10 '21 at 21:05
  • Don't do any of these. Use the standard (and already mentioned) `Dim bmp As Bitmap = TryCast(obj, Bitmap)`. If `Option Strict` is ON and `Option Infer` is OFF, then `Dim` acts like c#'s `var, so can shorten this to `Dim bmp = TryCast(obj, Bitmap)`. – ToolmakerSteve Aug 03 '21 at 10:18