Simple equivalent of “With” statement in C#

Consider the following class in C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Person
	{
		private string name;
		private int age;

		public string Name{
			get {return name;}
			set { name = value; }
		}

		public int Age{
			get {return age;}
			set { age = value; }
		}
	}

If I want to set the value of Name and Age property on the instance of Person class, I’ll need to refer to that instance for every property I need to set in the code. For example:

1
2
3
var person = new Person();
person.Name = "Super Man";
person.Age = 30;

It would have been great if C# had an equivalent of VB’s “With..End” statement, where we could refer to the instance of Person class only once and then refer to properties only.

Today, I came across this post “mucking about with hashes…“, which shows how C# lambdas could be used as hashes. Using this concept, I implemented a simple extension method that simulates the behavior of VB’s “With..End” statement to some extent.

Here is the code for extension method:

1
2
3
4
5
6
7
8
9
10
11
12
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);
				};
		}
	}

Using this extension method, we can set the value of properties on instance of Person class as follows:

1
2
3
4
5
var person = new Person();
person.Set(
	Name => "Super Man",
	Age => 30
);

Isn’t that cool?