11/23/07

Jacob Carpenter on named arguments in C#

Jacob Carpenter has an interesting post called Named parameters { Part = 2 }. As immutable types are very trendy these days (good!), questions arise how to initialize them. C# 3.0 has Object Initializers (where IntelliSense even kindly shows you the list of remaining uninitialized properties), but unfortunately we cannot use it because it requires the properties to be settable. Jacob came up with a pretty cool trick to use anonymous types to get a syntax similar to object initializers and still call into a constructor. This technique is somewhat similar to casting by example, where we also abuse anonymous types to reach our goal.

To further improve Jacob's strategy, I would probably turn NamedArguments into a factory and make it responsible for instantiating the CoffeeOrder object as well. One could use Activator.CreateInstance to create an instance of the CoffeeOrder type and return it directly instead. Thus, the code for initializing the object could be further reduced to:

var order1 = NamedArgs.For<CoffeeOrder>(new
{
DrinkName = “Drip”,
SizeOunces = 16,
});

No comments: