C# with keyword equivalent

There’s no with keyword in C#, like Visual Basic. So you end up writing code like this:

this.StatusProgressBar.IsIndeterminate = false;
this.StatusProgressBar.Visibility = Visibility.Visible;
this.StatusProgressBar.Minimum = 0;
this.StatusProgressBar.Maximum = 100;
this.StatusProgressBar.Value = percentage;

Here’s a work around to this:

this.StatusProgressBar.Use(p =>
{
  p.IsIndeterminate = false;
  p.Visibility = Visibility.Visible;
  p.Minimum = 0;
  p.Maximum = 100;
  p.Value = percentage;
});

Saves you repeatedly typing the same class instance or control name over and over again. It also makes code more readable since it clearly says that you are working with a progress bar control within the block. It you are setting properties of several controls one after another, it’s easier to read such code this way since you will have dedicated block for each control.

It’s a very simple one line function that does it:

public static void Use<T>(this T item, Action<T> work)
{
    work(item);
}

You could argue that you can just do this:

var p = this.StatusProgressBar;
p.IsIndeterminate = false;
p.Visibility = Visibility.Visible;
p.Minimum = 0;
p.Maximum = 100;
p.Value = percentage;

But it’s not elegant. You are introducing a variable “p” in the local scope of the whole function. This goes against naming conventions. Morever, you can’t limit the scope of “p” within a certain place in the function.

Update: Previously I proposed a way to do it without generic extention method which was not so clean. Andy T posted this cleaner solution in comments.

Shout it

4 Comments

  • I too sorely miss the with keyword from pascal. However, you can actually limit scope variables anywhere you want. For example:

    {
    var p = this.StatusProgressBar;
    p.IsIndeterminate = false;
    p.Visibility = Visibility.Visible;
    p.Minimum = 0;
    p.Maximum = 100;
    p.Value = percentage;
    }

    Keeps p only active within the curly braces

  • To limit the scope of a variable, simply place it between two curly brackets..

    public void method(){
    // some code

    {
    var p = this.StatusProgressBar;
    p.IsIndeterminate = false;
    p.Visibility = Visibility.Visible;
    p.Minimum = 0;
    p.Maximum = 100;
    p.Value = percentage;
    }

    // some more code where p is out of scope!
    }

    Cheers,
    Wes

  • Why not:

    public static void With(this T item, Action work) {
    work(item);
    }

    Then:

    this.StatusProgressBar.With(pb => {
    pb.Visiblity = false;
    });

    ... seems a bit cleaner

  • Very good idea Andy! I have updated the post with your solution.

Comments have been disabled for this content.