I moved from Visual Basic to C# when I migrated to .Net back on ’04. I have never regretted this. C# is so much nicer a language in my opinion. One of the things I especially like about C# is its conciseness. I hate typing.

The one and only thing I missed from VB was the WITH statement. It drove me nuts that in C# for all its brevity, if I needed to do half a dozen things with Object.Child.Grandchild.GreatGrandchild, I had to write that whole thing out or put GreatGrandchild in a local variable like so:

Object.Child.Grandchild.GreatGrandchild.Property1 = 1;
Object.Child.Grandchild.GreatGrandchild.Property2 = 2;
Object.Child.Grandchild.GreatGrandchild.Property3 = 3;
Object.Child.Grandchild.GreatGrandchild.Property4 = 4;

The advent of object initializers in C# 3.0 alleviated the primary use case for the With statement. But object initializers don’t do much for the above case or any situation where you have a pre-existing instance.

I recently realized though that I can get 99% of the way there with a combination of two other C# 3.0 features, extension methods and lambda expressions. Putting the two together, I came up with the following method:

public static void With<T>(this T obj, Action<T> action)
{
    action(obj);
}

Which lets me rewrite the example code like this:

Object.Child.Grandchild.GreatGrandchild.With(x =>
    {
        x.Property1 = 1;
        x.Property2 = 2;
        x.Property3 = 3;
        x.Property4 = 4;
    });

Its not perfect and I can see that depending on your stylistic preferences this might drive you nuts, but I think its some very clean code.

Author’s Update:

I recently discovered that Anay Kamat posted a different solution on his blog a way back in ’09. His approach uses reflection and results in a different usage syntax. I recommend you take a look and use whichever approach you like best.