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.

3 Responses to “The ”as” operator in C#”

  1. ActiveEngine Sensei Says:

    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

  2. kwiksand Says:

    I made the mistake of thinking it was exactly the same as:

    string s = (string)Cache[cacheKey];


  3. I use it all the time :) I almost never do an explicit cast, I think it’s much uglier then as.


Leave a Reply