The ”as” operator in C#
December 4, 2007
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.
December 4, 2007 at 13:54
Miguel Castro used the “as” operator in his code for a DNR TV screencast. But you’re right, this is not often used.
Here’s the link if you’re interested:
http://www.dnrtv.com/default.aspx?showNum=69
December 4, 2007 at 17:14
I made the mistake of thinking it was exactly the same as:
string s = (string)Cache[cacheKey];
March 12, 2008 at 21:11
I use it all the time :) I almost never do an explicit cast, I think it’s much uglier then as.