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.


4 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:

  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.

  4. Igal Nassi Says:

    Here I my few cents…

    I think it is plain wrong to use the As keyword for the most part, although there may be valid cases. If we need to take your code as an example, if you receive something that cannot be casted to string from the cache, the caller will think that the cache does not have the specific entry. However it may very well have it. So you are merging the case of “not found in cache” and “not castable to string” into the same bucket, which might have different meanings to the caller.

    The second and more important reason is it is SOOOO much slower than actual casting. I don’t know if you are in an environment where performance is a big issue.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: