Wednesday, October 21, 2009

Adventures in Office Interop and C# 4.0

I had a chance earlier to play with the new features introduced to C# 4.0 for the support of Office Interop. There are a couple of notable features.

First, Type.Missing is no longer required to pass into COM calls. This means no more:

wbs.Open(@"somefile.xlsx", missing, missing, missing, 
missing, missing, missing,
missing, missing, missing,
missing, missing, missing,
missing, missing);

Instead you can opt for:

wbs.Open(@"somefile.xlsx");

Readability FTW!

Other changes include the ability to use the indexed methods ("get_Range" for example) using indexers. Now, instead of:

Range range = ws.get_Range("A1", "A1");

You can use:

Range range = ws.Range["A1"];

Combined with the optional parameters, this makes for another win for readability.

In some situations, this "inferred property" addition makes things even more readable. How many times when setting a value in Excel Interop have you done this:

range.set_Value(XlRangeValueDataType.xlRangeValueDefault, i);

Yeah, not too pretty. Try this on instead:

range.Value = i;

Uh-huh. Yep. Much, much more readable.

That is all.