VB.NET "With...End With" In C#

Posted on January 23rd, 2014

One of my favorite things about VB.NET is the "With...End With" statement. Let's take a look:

Dim objPerson As New Person
With objPerson
     .FirstName = "Dave"
     .LastName = "Sanders"
     .Age = 36
     .Phone = "555-5555" End With
Versus the following:

Dim objPerson As New Person
objPerson.FirstName = "Dave"
objPerson.LastName = "Sanders" objPerson.Age = 36
objPerson.Phone = "555-5555"
This may not look like a huge difference at first, but it is incredibly useful when performing many operations on the same object. By using the "With" statement, you can save a lot of repetitive typing, and create an easy to read block of code.

Unfortunately, this isn't available in C#. It could be argued that the "With" hurts readability, and you're better off using a variable with a meaningful name to accomplish the same task. Personally, I think the "With" statement greatly improves readability, and it doesn't even have a performance hit on the compiler.

To mimic similar behavior in C#, your could do something like this:

var objPerson = new Person
{
     FirstName = "Dave",
     LastName = "Sanders",
     Age = 36,
     Phone = "555-5555"
};

This is also a fairly elegant solution, but it is often overlooked by many C# developers. It really is a personal preference, and for me, the less repetition the better.


comments powered by Disqus
Andrew Backes

A Software Engineer living in Milwaukee, WI. Passionate about web/software development, tech, open source, and gaming.