Click here to Skip to main content
15,891,136 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 
It'd be an essentially useless addition, but It'd be interesting to see the 'using' statement overloaded for creating a scope:

using {
// code in a child scope of the method body here
}

But again, it'd be pointless since you get the same thing with just the braces. I agree that it does look a little sparse that way.

One place I use this a lot are in switches:

switch (variable) {
case 1: { // ** - child scope for local variables
// Case 1 code here
break;
}

case 2: {
// etc...
break;
}
}

Bad programming practice, yes, but I use this for quick programs where I'm more interested in getting something done right now than I am in a sustainable architecture.
GeneralI don't like creating needless delegates; to my mind, simply... Pin
supercat927-May-11 5:47
supercat927-May-11 5:47 

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.