6 Replies
It's pretty much just a nullable cast
Type-testing operators and cast expressions test the runtime type o...
The
is
and as
operators test the type of an object. The typeof
keyword returns the type of a variable. Casts try to convert an object to a variable of a different type.Here's the keywords overview on MSDN https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/
Try to avoid casting as much as possible. Use
as
if you're not sure if the cast is valid, and follow it with a null check. Use explicit casting (type)variable
when you're sure of the cast.Just to add to that -- always check for null after using
as
. If you expect the cast to succeed, always use a proper (T)
cast. The reason is that it's a lot easier to debug a failed cast if you used a proper (T)
cast, as the exception is thrown at the point that the cast failed and the exception message is helpful, as opposed to getting a NullReferenceException
at some point after a failed as
cast with no information on why the cast failedWas this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.