The ”as” operator in C#

by: Peter Hultgren (Sogeti)

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

Tags:


Comments

  1. Too True.. I think this will change once people start using the CMS sample templetes and demo templates. Its nice to see how clean the code has become :)
Post a comment    
User verification Image for user verification  

About me

I am a 27 years old consultant at Sogeti in Stockholm, Sweden. I am working mainly with developing solutions in EPiServer, which I've been doing since 2006. I also write at Microserf and you can e-mail me at this address: peter.microserf@gmail.com.

Syndications


Archive


Tag cloud

EPiTrace logger