Visual Basic .NET Language Disposable objects Declaring more objects in one Using

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Sometimes, you have to create two Disposable objects in a row. There is an easy way to avoid nesting Using blocks.

This code

Using File As New FileStream("MyFile", FileMode.Append)
    Using Writer As New BinaryWriter(File)
        'You code here
        Writer.Writer("Hello")
    End Using
End Using

can be shortened into this one. The main advantage is that you gain one indentation level:

Using File As New FileStream("MyFile", FileMode.Append), Writer As New BinaryWriter(File)
    'You code here
    Writer.Writer("Hello")
End Using


Got any Visual Basic .NET Language Question?