- Home /
What is the difference between "prefix-casting" (Type)variable - and "as-casting" (variable as Type)?
I know there's two ways of casting in C#:
Prefix-casting:
MyType newVariable = (MyType) myVariable;
As-casting:
MyType newVariable = myVariable as MyType;
What is the difference?
Answer by jashan · Sep 11, 2010 at 01:08 PM
Prefix-casting is usually quite a bit safer because if you run into an exception, it gives you a TypeCastException telling you exactly what's going on. As-casting on the other hand will simply return null if that cast is not allowed. This creates a couple of difficulties when there is a problem: a) you don't know if myVariable was null or of the wrong type, b) newVariable might be null and this might give you a NullReferenceException at a later point in time ... which might make debugging harder.
However, as-casting has one significant advantage: It's much faster. In most cases, this "much faster" won't matter much, but if you're on the iPhone or Android, or when you're doing those casts thousands of times per frame, it may make a difference.
In both cases, it's good practice to add some checks or exception handling; depending on what your exact needs are:
if (myVariable is MyType) {
MyType newVariable = (MyType) myVariable;
// ... do whatever you wanna do with newVariable
}
Or
try {
MyType newVariable = (MyType) myVariable;
// ... do whatever you wanna do with newVariable
} catch (InvalidCastException exc) {
// do whatever needs to be done if that exception occurs
}
Or
if (myVariable is MyType) {
MyType newVariable = myVariable as MyType;
// ... do whatever you wanna do with newVariable
}
Or
MyType newVariable = myVariable as MyType;
if (newVariable != null) {
// ... do whatever you wanna do with newVariable
} else {
// ignore or send a warning or whatever you need to
// do when either myVariable is null or not of the
// correct type
}
In any case, it helps when you understand exactly what you're doing ;-)
Actually it's not true that as-casting is faster. The difference between the two is very tiny but if you want to make the distinction: prefix-casting is faster than as-casting.
Answer by aerinzero · Apr 08, 2012 at 03:08 PM
Another difference I noticed: (Unity 3.5, C#)
//data is an arrayList with some Vector3's and other types stored in it. Vector3 spawn = data[0] as Vector3; //THIS FAILS Vector3 spawn = (Vector3)data[0]; // THIS WORKS
Becouse Vector3 is a value type and these can't have a value of null. If you would cast "as Vector3?" than everything will work just fine. It's not a Unity connected thing.
Your answer
Follow this Question
Related Questions
Can someone explain 'Using ..." and "MonoBehaviour" in C# 7 Answers
Can some one help me with splash screen? 1 Answer
What are the Syntax Differences in C# and Javascript? 7 Answers
How to make door open and close with Input.GetButtonDown? 1 Answer
How to check if variable defined in script is present in shader? 1 Answer