I was reading through someone else’s C# code the other day when I saw something that wasn’t immediately clear. It went something like this:
[code]
Object o;
for (int i=0; i < myCollection.count; i++) {
o = myCollection[i] as SomeObjectType; // Huh?
if (o != null) {
// Do something with 'o'...
break;
}
}
[/code]
While the cast seems clear enough, there are a few things to be aware of. If the above cast fails, it assigns a null value to 'o'. If the null value is not handled immediately, you may not realize the problem until some time later when you run into the null reference.
[code]
Object o;
// As-casting - Returns null if the cast fails!
o = myCollection[i] as SomeObjectType;
// Prefix casting - throws an exception if the cast fails!
o = (SomeObjectType)myCollection[i];
[/code]
There may be a performance benefit to the As-cast but I'm much more comfortable knowing that my cast exceptions were handled properly using the Java-esque Prefix cast.
Category: Web
getElementById fails on IE
While working on a simple test page, I wanted to use getElementById to get an Image object from JavaScript. I quickly wrote up the code and tried it. Firefox was fine but it failed on my IE7 with “Microsoft JScript runtime error: Object doesn’t support this property or method”. It took some digging to see what the problem was.
First thing I checked was that I used both element Name and Id and that they were the same. I *always* do that given that IE will use whichever one matches the desired string. After reading a few blog posts about common problems but with no good ideas I went back to my code and reviewed it carefully. It turns out that I used the same name for my element and my local JavaScript variable. That by itself isn’t a problem but what made it an issue for me was that I failed to initialize my variable with the “var” keyword.
See the code below for the example:
[code]
Do Something


[/code]