Erik Porter's Blog

Life and Development at Microsoft and Other Technology Discussions

News

    VB Import Alias

    M. Keith Warren points out that in C#, you can use the using statement to also create an alias to a particular class to save you some typing.  I honestly thought that didn't work, but I'm glad I'm wrong, that's cool.  VB.NET can do the same thing.

    Imports

    cfg = System.Configuration.ConfigurationSettings

    Thought I'd also mention another way the using statement can be used in C# (but unfortunately has no equivelant in VB.NET) to automatically dispose of a variable when you're done (when the block of code ends).

    using (SqlConnection con = new SqlConnection())
    {
        
    // do something with con
    }

    Even if you declare the variable outside of the parens, it will still call Dispose on “con” after the last curly brace.  You can also declare as many variables inside the using parens seperated by commas as you want and they will all be disposed of afterwords for you.

    Comments

    mark said:

    ... but they all have to be of the same type, right?
    # August 13, 2003 10:23 AM

    Scott Mitchell said:

    Neat trick with the using block. Although the objects get cleaned up after they go out of scope, so if you make sure your methods are short and to the point you should be ok, no?

    I've not tried this, but does C# create scopes with {} just like C++? With C++ you could do stuff like:

    void main()
    {
    {
    int x;
    // x's lifetime is only within this scope
    }
    // x can't be referenced here, it has been reclaimed
    }

    I wonder if C# lets you do that, or if you HAVE to use using.... hrm.
    # August 13, 2003 5:19 PM

    Adam Kinney said:

    C# does scope variables the same way as C++. So without the using block, a class instance variable is dereferenced but not disposed.
    # August 14, 2003 5:00 PM

    Cory Smith said:

    It looks like 'using' functionality will be in the next release of VB.NET. So it's something to look forward to.
    # October 31, 2003 5:48 PM

    HumanCompiler said:

    Oh I know...I would've said something when I posted this, but I was under NDA at the time ;)
    # October 31, 2003 7:13 PM

    Fan said:

    I think the best thing of VB is 'With'

    With people

     .Name = ""

     .Age = 20

    End With

    But the 'Dim a As Integer' sucks

    And the 'Property' sucks too

    # January 15, 2008 1:37 AM