Click here to Skip to main content
15,891,529 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

C# equivalent of VB's With keyword

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
27 May 2011CPOL 12.2K   1   4
You can limit the scope of 'p' inside your function:private void Whatever() { DoStuffHere(); // 'p' is not in scope. { var p = this.StatusProgressBar; // 'p' is in scope. p.IsIndeterminate = false; p.[etc] } // 'p' is not in...
You can limit the scope of 'p' inside your function:

private void Whatever() {
    DoStuffHere();
    // 'p' is not in scope.

    {
        var p = this.StatusProgressBar;
        // 'p' is in scope.

        p.IsIndeterminate = false;
        p.[etc]
    }

    // 'p' is not in scope.
    DoMoreHere();
}


Notice the open and close braces - they create a scope that 'p' will not be leaked from.

Personally, I like your idea better - but it *is* possible to limit scope within a function.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 exactly what I thought Pin
johannesnestler15-Feb-12 3:40
johannesnestler15-Feb-12 3:40 
GeneralReason for my vote of 5 Yep, thats what I do too. Having the... Pin
Doc Lobster24-Sep-11 0:14
Doc Lobster24-Sep-11 0:14 
GeneralIt'd be an essentially useless addition, but It'd be interes... Pin
dzCepheus27-May-11 7:30
dzCepheus27-May-11 7:30 
GeneralI don't like creating needless delegates; to my mind, simply... Pin
supercat927-May-11 5:47
supercat927-May-11 5:47 
I don't like creating needless delegates; to my mind, simply creating a temporary variable is cleaner. I do wish there were a standard idiom for introducing a block purely for scoping purposes; "if(1)" seems a little icky, and blocks which don't control a conditional or looping construct often look like something's "missing". BTW, the "With" construct in VB can be used with value types in ways that would require multiple variables in C. For example, if Foo is an array of a value type, "With Foo(I,J)" will effectively latch the values of Foo, I, and J; I don't know if it avoids the recomputation of the array subscript for each access.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.