.net – How does the Using statement translate from C# to VB?

.net – How does the Using statement translate from C# to VB?

Using has virtually the same syntax in VB as C#, assuming youre using .NET 2.0 or later (which implies the VB.NET v8 compiler or later). Basically, just remove the braces and add a End Using

Dim bitmap as New BitmapImage()
Dim buffer As Byte() = GetHugeByteArrayFromExternalSource()
Using stream As New MemoryStream(buffer, false)
    bitmap.BeginInit()
    bitmap.CacheOption = BitmapCacheOption.OnLoad
    bitmap.StreamSource = stream
    bitmap.EndInit()
    bitmap.Freeze()
End Using

You can get the full documentation here

EDIT

If youre using VS2003 or earlier youll need the below code. The using statement was not introduced until VS 2005, .NET 2.0 (reference). Thanks Chris!. The following is equivalent to the using statement.

Dim bitmap as New BitmapImage()
Dim buffer As Byte() = GetHugeByteArrayFromExternalSource()
Dim stream As New MemoryStream(buffer, false)
Try
    bitmap.BeginInit()
    bitmap.CacheOption = BitmapCacheOption.OnLoad
    bitmap.StreamSource = stream
    bitmap.EndInit()
    bitmap.Freeze()
Finally
    DirectCast(stream, IDisposable).Dispose()
End Try

Its important to point out that using is actually compiled into various lines of code, similar to lock, etc.

From the C# language specification….
A using statement of the form

using (ResourceType resource = expression) statement

corresponds to one of two possible expansions. When ResourceType is a value type, the expansion is

{
    ResourceType resource = expression;
    try {
        statement;
    }
    finally {
        ((IDisposable)resource).Dispose();
    }
}

Otherwise, when ResourceType is a reference type, the expansion is

{
    ResourceType resource = expression;
    try {
        statement;
    }
    finally {
        if (resource != null) ((IDisposable)resource).Dispose();
    }
}

(end language specification snippet)

Basically, at compile time its converted into that code. There is no method called using, etc. I tried to find similar stuff in the vb.net language specification but I couldnt find anything, presumably it does the exact same thing.

.net – How does the Using statement translate from C# to VB?

That would be something like this:

Dim bitmap As New BitmapImage()
Dim buffer As Byte() = GetHugeByteArray()
Using stream As New MemoryStream(buffer, False)
    bitmap.BeginInit()
    bitmap.CacheOption = BitmapCacheOption.OnLoad
    bitmap.StreamSource = stream
    bitmap.EndInit()
    bitmap.Freeze()
End Using

Leave a Reply

Your email address will not be published.