Why it is time to retire the old cast operator in C#: MyType t= (MyType)o

Why it is time to retire the old cast operator in C#:  MyType t= (MyType)o

 These days I am reading the book "Effective C#: 50 Specific Ways to improve C#" by Scott Meyers. After using C# for many years, you get into the mindset: "I know everything already". But this book really inspires me to rethink the basics I am using every day and make a step forward in sharpening my C# skills.

The goal of these blog series is not to copy the book but write down my thoughts in a compressed way on certain topics. So when I will wonder in the future "Why am I doing this" I can just come back and re-read it and also maybe for you guys who don't have the time to give you a quick overview of the little things we use everyday without knowing.

So enough talk time for the topic:
Why is it time to retire the old cast operator in C#

Don't get me wrong there are reasons (maybe 0.05%) but it is time to explore the better casting options we have in C#:

is, as and typeof are the new heroes!

So what is the big difference in a nutshell:

is compares if an object is of specific type and returns true or false.  Every is operator could be replaced with
as will attempt to cast it into the specific type and returns either the type or null
typeof checks if the actual type of the object (A comparison of a derived type does not match the parent type)

But let's have a look at some code:

First same basic class definition:

public class DeriveTomType : TomType
{ public int Age { get; set; }
}

public class TomType
{ public virtual string Name { get; set; }
}

Now the actual test code:

object o = new DeriveTomType();if(o is TomType)
{
Console.WriteLine("is: o is TomType");
}
//no try catch required. If cast fails, t will be null. //No exception thrown TomType t = o as TomType;if (t != null)
{
Console.WriteLine("as: o is TomType");
}
//the same in one line: t = null;
if ((t = o as TomType) != null)
{
Console.WriteLine("as Replacement: o is TomType");
}

if( o.GetType()!= typeof(TomType))
{
Console.WriteLine("GetType: o is not TomType");
}

And the result is

 is: o is TomType
as: o is TomType
as: o is TomType
getType: o is not TomType

The interested reader might think: "Wow this is cool. But why should I not use the cast operator anymore again?"

And the quick answer is:
- No try catch required => Easier on the CLR (this is the main reason)
- Easier to read code  (very important to me)

I know there is more to it, but for this blog entry I think this is good enough.
Otherwise I would contradict my intention: Keep it short AND GOOD ENOUGH!

Tom

This article is part of the GWB Archives. Original Author: ftom

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.