COM Example in C# 4.0

Here is a larger Office automation example that shows many of the new C# features in action.

using System;
using System.Diagnostics;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;

class Program
{
static void Main(string[] args) {
var excel = new Excel.Application();
excel.Visible = true;

excel.Workbooks.Add(); // optional arguments omitted

excel.Cells[1, 1].Value = "Process Name"; // no casts; Value dynamically
excel.Cells[1, 2].Value = "Memory Usage"; // accessed

var processes = Process.GetProcesses()
.OrderByDescending(p => p.WorkingSet)
.Take(10);

int i = 2;
foreach (var p in processes) {
excel.Cells[i, 1].Value = p.ProcessName; // no casts
excel.Cells[i, 2].Value = p.WorkingSet; // no casts
i++;
}

Excel.Range range = excel.Cells[1, 1]; // no casts

Excel.Chart chart = excel.ActiveWorkbook.Charts.
Add(After: excel.ActiveSheet); // named and optional arguments

chart.ChartWizard(
Source: range.CurrentRegion,
Title: "Memory Usage in " + Environment.MachineName); //named+optional

chart.ChartStyle = 45;

chart.CopyPicture(Excel.XlPictureAppearance.xlScreen,
Excel.XlCopyPictureFormat.xlBitmap,
Excel.XlPictureAppearance.xlScreen);

var word = new Word.Application();
word.Visible = true;

word.Documents.Add(); // optional arguments

word.Selection.Paste();
}
}

The code is much more terse and readable than the C# 3.0 counterpart.

Note especially how the Value property is accessed dynamically. This is actually an indexed property, i.e. a property that takes an argument; something which C# does not understand. However the argument is optional. Since the access is dynamic, it goes through the runtime COM binder which knows to substitute the default value and call the indexed property. Thus, dynamic COM allows you to avoid accesses to the puzzling Value2 property of Excel ranges.

Posted in: programming | Tags: c# linq c# 4.0 microsoft.office.interop.excel microsoft.office.interop.word getprocesses processxlcopypictureformat xlbitmap xlscreen excel.xlpictureappearance.xlscreen