.Net Tips – using as vs casting in C#

Yan Cui

I help clients go faster for less using serverless technologies.

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. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


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 *