Friday, April 11, 2008

Casting with "as" in C#

C# provides a couple of methods for casting. One way is the way most familiar to C/C++/Java programmers:


Foo foo = (Foo)bar;


The second way is through the use of the "as" keyword, which may feel more comfortable to ex-VB programmers (since it also has an "as" keyword):


IFoo foo = someObject as IFoo;


...and the great advantage of the latter form is that "as" returns null if the object does not support the type (or interface) in question, instead of throwing an exception. This is really handy if you're trying to do invoke a method at runtime and you want to only do it to the object if it supports the interface:


if (foo != null)
{
foo.DoSomethingInterestingNow();
}


I guess you could also do this with "is" and a cast too:


if (bar is IFoo)
{
foo = (IFoo)bar;
// or:
//foo = bar as IFoo;
foo.DoSomethingInterestingNow();
}

Thursday, April 3, 2008

How to Automatically Generate XML Comments in C# using Visual Studio .NET 2005

(Since I don't have a desktop software development blog right now I figured I'd better just put this here, since it could apply to C# programming with ASP.NET...)

To automatically generate XML comments in C# using VS.NET 2005, all you have to do is type a triple-whack ("///") in your code before a method definition and the IDE will build out the XML for you.

I accidentally stumbled on this on the same day I was trying to find out how to do it, which doesn't happen too often. I actually found it while nosing around in the VS.NET preferences:

Tools --> Options --> Text Editor --> C# --> Advanced

...which has an "XML Documentation Comments" section and a "Generate XML documentation comments for ///" checkbox.

You really need your miner's helmet for that one! Whew!