❔ As Keyword

when should you use the "as" key word?
6 Replies
DaVinki
DaVinki2y ago
It's pretty much just a nullable cast
DaVinki
DaVinki2y ago
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.
FusedQyou
FusedQyou2y ago
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.
canton7
canton72y ago
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 failed
Accord
Accord2y ago
Was 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.
Want results from more Discord servers?
Add your server