.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; }
}
Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless.

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Check out my new course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, callbacks, nested workflows, design patterns and best practices.

Get Your Copy