Search code examples
c#excelvbacomvsto

VSTO: manipulating COM objects ("one dot good, two dots bad")


Coming from an Excel VBA background I would frequently write code such as:

Range("myRange").Offset(0, 1).Resize(1, ccData).EntireColumn.Delete

I'm now moving to VSTO, and have been reading about RCW counters, etc., and the need to explicitly release COM objects. The basic advice seems to be: don't chain together references to Excel objects (as I have above) - hence "one dot good, two dots bad". My question is, am I correct that the above code is not the way to go in VSTO? If so, does that mean that I would need to explicitly declare the 3 ranges implied in the above chain (Offset, Resize & EntireColumn)?

Or even how about something like:

rng.Columns.Count

where rng is a declared Range? Should I be assigning a name to rng.Columns in order to obtain the number of columns in the range??


Solution

  • There is very detrimental cargo cult behind that "two dot rule" silliness, it completely fails to keep C# programmers out of trouble since version 4. And it endlessly more painful than the simple way to make Office programs quit on demand.

    But this is not a problem you have at all, the cargo cult only applies to an out-of-process program that use Automation to activate an Office program. Your code in fact runs inside the Office program, you of course don't care when the program terminates. Because that terminates your code as well.

    Just write your code the way you'd write regular C# code, the GC does not need any help.