Sunday, March 3, 2013

C# V/S VB.Net variable scope in using block

Recently there was a scenario faced by one of our colleague which brought one more difference between C# and VB.Net. Now it is related to the 'using' block.The difference can be summarized as

"In C# if we reinitialize a variable in the header of using block which is declared already in the higher scope,it overwrite the already declared variable.But in VB.Net if we try reinitialize already declared variable it will create a new variable only for the 'using' block.

This is little difficult to understand. Lets see in code.

Code Output
class Disposable : IDisposable
{
    string input;
    public Disposable(string arg)
    {
        input = arg;
    }
    public void Display()
    {
        Console.WriteLine(input);
    }
    public void Dispose(){}
}
public class Program
{
    static Disposable dispo = new Disposable("higher level");
    static void Main(string[] args)
    {
        using (dispo = new Disposable("using block level"))
        {
            dispo.Display();
        }
        dispo.Display();
    }
}


using block level

using block level


Public Class Disposable
    Implements IDisposable
    Dim input As String
    Public Sub New(arg As String)
        input = arg
    End Sub
    Public Sub disp()
        Console.WriteLine(input)
    End Sub
    Public Sub Dispose() Implements IDisposable.Dispose 'Implement later
    End Sub
End Class

Module Module1
    Dim dispo As New Disposable("higher level")
    Sub Main()

        Using dispo = New Disposable("using block level")
            dispo.disp()
        End Using
        dispo.disp()
    End Sub
End Module


using block level

higher level

It is clear that at the first look the code looks same. This type of scenarios may come when we do a C# to VB.Net conversion or vice versa.
If you want to get the C# behavior in VB.Net you need to move the initialization part out of using block header.Code below

dispo = New Disposable("using block level")
Using dispo
    dispo.disp()
End Using
dispo.disp()

No comments: