Blog Archives

With Statement in C# .Net

If you’re stumbling across this article, chances are you may be looking for a replacement for VB .Net’s “with” statement.

Sadly, there is no exact replacement, but there are alternatives which are equally helpful.

Given a basic class “Robot” below:

public class Robot {
public string name {get;set;}
public int age {get;set;}
}

Variable Declaration

If you were using “With” simply for initial variable declaration so you didn’t have to specify long constructors, you can use the following instead:

public Robot MyRobot = new Robot() {name="Ronnie-5", age=3300};

If you were using “With” to stay within the context of an object while performing a specific task, then there is no direct equivalent, although I would definitely advise you to try “using” if you’re not already.

using (Robot MyRobot = new MyRobot()) {
MyRobot.name="Ronnie-5";
MyRobot.age=3300;

if (MyRobot.name=="something") {
//do something
}
//when finished it will automatically dispose for you
}

Extension Methods

Another approach, if your concern is code readability and brevity is to begin using some generic class extension methods in your project to help you simplify common tasks. (see example below)

(Kudos to Anay Kamat for clean and reusable code.)

public static class MetaExtensions
{
	public static void Set(this object obj,params Func<string,object>[] hash){
			foreach(Func<string,object> member in hash){
				var propertyName = member.Method.GetParameters()[0].Name;
				var propertyValue = member(string.Empty);
				obj.GetType()
					.GetProperty(propertyName)
						.SetValue(obj,propertyValue,null);
			};
	}
}

So you could also alternatively replace “With” by adding the above class extension method and simply doing:

var myrobot = new Robot();
myrobot.Set(
	name=> "Ronnie-5",
	age=> 3300
);

//or as a one-liner

myrobot.Set(name=>"othername",age=>otherage);

Now this is technically more lines of code than simply declaring initialization values in the first code snippet, but the upside is… well actually, I’m not sure of the upside, but it’s definitely cool. 🙂

References
Anay Kamat (blog), http://anaykamat.com/2009/08/09/simple-equivalent-of-with-statement-in-c-sharp/
MSDN (Extension Methods), http://msdn.microsoft.com/en-us/library/bb383977.aspx

Advertisement