The ”as” operator in C#
I don’t know if it’s just me, but I don’t see people using the ”as” operator in C# a lot when I read code. It’s a shame, because it’s really nifty. For example, you can use it like this when you retrieve something from the cache:
string s = Cache[cacheKey] as string;
if(s != null) {
return s;
}
else {
// Set s to a new value
Cache[cacheKey] = s;
return s;
}
This way you don’t have to explicitly check the type of the cache contents. If it can’t be casted, s will just contain null instead.
04 December 2007