[ACCEPTED]-Casting: (NewType) vs. Object as NewType-.net
The former will throw an exception if the 9 source type can't be cast to the target 8 type. The latter will result in sc2 being 7 a null reference, but no exception.
[Edit]
My 6 original answer is certainly the most pronounced 5 difference, but as Eric Lippert points out, it's not 4 the only one. Other differences include:
- You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value
- You can't use 'as' to convert things, like numbers to a different representation (float to int, for example).
And 3 finally, using 'as' vs. the cast operator, you're 2 also saying "I'm not sure if this will 1 succeed."
Also note that you can only use the as keyword 2 with a reference type or a nullable type
ie:
double d = 5.34;
int i = d as int;
will 1 not compile
double d = 5.34;
int i = (int)d;
will compile.
Typecasting using "as" is of course 10 much faster when the cast fails, as it avoids 9 the expense of throwing an exception.
But 8 it is not faster when the cast succeeds. The 7 graph at http://www.codeproject.com/KB/cs/csharpcasts.aspx is misleading because it doesn't 6 explain what it's measuring.
The bottom line 5 is:
If you expect the cast to succeed (i.e. a 4 failure would be exceptional), use a cast.
If 3 you don't know if it will succeed, use the 2 "as" operator and test the result 1 for null.
Well the 'as' operator "helps" you bury your problem way lower because when it is provided an incompatible 7 instance it will return null, maybe you'll 6 pass that to a method which will pass it 5 to another and so on and finally you'll 4 get a NullReferenceException which will 3 make your debugging harder.
Don't abuse it. The 2 direct cast operator is better in 99% of 1 the cases.
A difference between the two approaches 2 is that the the first ((SomeClass)obj) may 1 cause a type converter to be called.
Here is a good way to remember the process 11 that each of them follow that I use when 10 trying to decide which is better for my 9 circumstance.
DateTime i = (DateTime)value;
// is like doing
DateTime i = value is DateTime ? value as DateTime : throw new Exception(...);
and the next should be easy 8 to guess what it does
DateTime i = value as DateTime;
in the first case if 7 the value cannot be cast than an exception 6 is thrown in the second case if the value 5 cannot be cast, i is set to null.
So in 4 the first case a hard stop is made if the 3 cast fails in the second cast a soft stop 2 is made and you might encounter a NullReferenceException 1 later on.
To expand on Rytmis's comment, you can't use the as keyword 2 for structs (Value Types), as they have 1 no null value.
All of this applies to reference types, value 10 types cannot use the as
keyword as they cannot 9 be null.
//if I know that SomeObject is an instance of SomeClass
SomeClass sc = (SomeClass) someObject;
//if SomeObject *might* be SomeClass
SomeClass sc2 = someObject as SomeClass;
The cast syntax is quicker, but 8 only when successful, it's much slower to 7 fail.
Best practice is to use as
when you don't 6 know the type:
//we need to know what someObject is
SomeClass sc;
SomeOtherClass soc;
//use as to find the right type
if( ( sc = someObject as SomeClass ) != null )
{
//do something with sc
}
else if ( ( soc = someObject as SomeOtherClass ) != null )
{
//do something with soc
}
However if you are absolutely 5 sure that someObject
is an instance of SomeClass
then use cast.
In 4 .Net 2 or above generics mean that you very 3 rarely need to have an un-typed instance 2 of a reference class, so the latter is less 1 often used.
For those of you with VB.NET experience, (type) is 2 the same as DirectCast and "as type" is 1 the same as TryCast.
The parenthetical cast throws an exception 2 if the cast attempt fails. The "as" cast 1 returns null if the cast attempt fails.
They'll throw different exceptions.
() : NullReferenceException 13
as : InvalidCastException
Which could help 12 for debugging.
The "as" keyword 11 attempts to cast the object and if the cast 10 fails, null is returned. The () cast operator 9 will throw an exception immediately if the 8 cast fails.
Only use the C# "as" keyword 7 where you are expecting the cast to fail 6 in a non-exceptional case. If you are counting 5 on a cast to succeed and unprepared to receive 4 any object that would fail, you should use 3 the () cast operator so that an appropriate 2 and helpful exception is thrown.
For code 1 examples and a further explanation: http://blog.nerdbank.net/2008/06/when-not-to-use-c-keyword.html
It's like the difference between Parse and 3 TryParse. You use TryParse when you expect 2 it might fail, but when you have strong 1 assurance it won't fail you use Parse.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.