.Net Tips – using as vs casting in C#

Runtime type conversion is something we all have to do from time to time, and in C#, type conversion is usually done using either the as keyword or casting.

Here’s a quick glance of how the two approaches differ:

Null reference Conversion failure User-defined conversion Performance
as Null Null Ignored Fast
casting Null Exception Used Slow

Prefer as to casting

In Bill Wagner’s Effective C# book, he recommends that you should use the as keyword whenever possible, because:

  • it’s more efficient at runtime, the as keyword (like the is keyword) does not perform any user-defined conversion. It will only succeed if the object is of the sought type (or derived from it) and never create a new object to satisfy a request.
  • requires less code because you don’t need a try-catch block in addition to a null check.

There are a few things you should keep in mind when using the as keyword:

  • it doesn’t work with value types because value types can never be null
  • don’t use the is keyword if you’re using as for type conversion, it’s redundant because these two statements are equivalent except the as version evaluates expression only once!
expression as type
expression is type ? (type) expression : (type) null

When you should use casting

That’s not to say that you should never use casting, a typical use I have found working with a Flash client is the need to convert business logic classes into AMFVO which are simple containers for a subset of the properties of the logic classes and none of the behaviour. In almost all cases like this I overload the implicit/explicit operator (see post on controlling type conversion here) and use casting to invoke my custom type conversions. The as keyword would not be appropriate in this case because the value object classes should never inherit from the business logic classes.

Gotcha!

Yup, there’s a gotcha with using casting, and a pretty big one at that too!

The user-defined conversion operators operate only on the compile-time type of an object. What this means is that if no conversion operator exists for the declared type of a variable the casting operation will fail even if a conversion operator exists for the runtime type of that variable. I.E.

void Main()
{
    Player player = new Player { Name = "Me" };
    PlayerDTO playerDTO = (PlayerDTO) player; // this succeeds

    object player2 = new Player { Name = "You" };
    PlayerDTO playerDTO2 = (PlayerDTO) player2; // this fails, throws runtime InvalidCastException

    object player3 = new Player { Name = "They" };
    PlayerDTO playerDTO3 = player3 as PlayerDTO; // this fails, returns null

    Player player4 = new Player { Name = "It" };
    PlayerDTO playerDTO4 = player4 as PlayerDTO; // this won't compile

}

public class Player
{
    public string Name { get; set; }

    public static explicit operator PlayerDTO(Player player)
    {
        return new PlayerDTO(player.Name);
    }
}

public class PlayerDTO
{
    public PlayerDTO(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }
}
  • Pingback: .Net Tips — using as vs casting in C# | theburningmonk.com | Learn Visual Studio()

  • http://unaico-sitetalk.com Tonie Pixley

    Heya…my very first comment on your site. ,I have been reading your blog for a while and thought I would completely pop in and drop a friendly note. . It is great stuff indeed. I also wanted to ask..is there a way to subscribe to your site via email?

  • http://www.howtobuildmywebsites.com/blog/index.php Dee Hofferber

    Would it be ok if I refer to this website, from my blog page? I’m planning to source as many bits of good info as I can.

  • theburningmonk

    Hi Dee, sure, feel free to refer :-)

  • theburningmonk

    Hi Tonie, if you subscribe to the RSS feed (http://theburningmonk.com/feed/) in Internet Explorer it’ll be added to the global list of RSS feeds in windows and will appear in Outlook’s RSS Feeds section.