Tuesday, May 02, 2006

The AS keyword in C# or Safe Casting

If you have ever used code like:
try {
obj1=(TypeObj1)obj2;
} catch {
obj1=null;
}

you need to read this.

The same thing can be written as:
obj1=obj2 as TypeObj1;

In case the conversion doesn't work, the value of obj1 will be null.
Be careful when you do this with value types that don't allow null.

Update:
Also, implicit casting will not work. A code like:
int i=5;
string s=i as string;

will have s being null, not "5".

You also have to be careful about using the "is" word. Code like
if (ctrl is Table) {
Table tbl=(Table)ctrl;
tbl...

actually casts ctrl twice!
a is b translates to (a as b)!=null.

So a nice piece of code would look like this:
Table tbl=ctrl as Table;
if (tbl!=null) {
tbl...

0 comments: