.Net Tips – using as vs casting in C#

Yan Cui

I help clients go faster for less using serverless technologies.

This article is brought to you by

The real-time data platform that empowers developers to build innovative products faster and more reliably than ever before.

Learn more

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; }
}

Whenever you’re ready, here are 4 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. Do you want to know how to test serverless architectures with a fast dev & test loop? Check out my latest course, Testing Serverless Architectures and learn the smart way to test serverless.
  3. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  4. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

5 thoughts on “.Net Tips – using as vs casting in C#”

  1. Pingback: .Net Tips — using as vs casting in C# | theburningmonk.com | Learn Visual Studio

  2. 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?

Leave a Comment

Your email address will not be published. Required fields are marked *