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