In this example neither of the two is necessary, so it makes no difference.
as
The operator as
should be used when you are not sure that the operation will work. Consider that there will be a conversion attempt, but if the object that should receive the value of that type fails, it will receive the null value. After using the as
It is essentially mandatory to check if the object is not null. Then you would. If you’re not doing this check you probably didn’t need this one casting, or you’ll have another mistake later, which could be a bigger problem finding out what’s going on.
The cost of that operator as
is even smaller, but when we make the check if it is not null ends up getting more or less the same thing.
C# 6
Normally you would make a if
to check if the value is null to decide what to do. In C# 6 there is an operator that does nothing if it is null. In some cases it is possible to use it to simplify the code, but not at all.
C# 7
It is possible to use Pattern matching and only create a new object when it confirms that the object type is the one expected.
C# 8
In this version that no longer encourages the use of null types, therefore the as
should fall into disuse and give way to the Pattern matching. The cast in parentheses will still be useful.
Cast
The cast classic, the second, requires you to be absolutely sure that the "conversion" will not fail. Any situation you will know that it will not fail you can use it. In many cases the cost of using it is zero.
One of the ways to be absolutely sure is to make a if
before doing the cast, but if you do this it is because you should use the as
. Be sure, if you need to check, it is because you do not have it. If you do this the performance will be worse and you can enter race condition.
This is a case you are only informing to the compiler that you can ensure that the type is the one the compiler expects. If your warranty does not conform at runtime the application will throw an exception that should not be handled, this is a programming error and must fix this error.
It also has the advantage of making conversions in type by value. These types cannot be null, so the as
would not work. Of course it does not include the types by value.
It can do type conversions when it is implemented on the type itself. The operator ()
can be implemented in explicit conversion types (it is also possible implicitly where an operator is not used). The as
is only allowed where the language leaves naturally, in natural conversions, usually just making a derivative type turn into a base type of it.
I won’t say it’s never necessary, but for the future I would forget the as
.
When you do the conversion using "as", if the code fails to do the conversion returned a null value and when you do the normal cast if the program fails to do the conversion will be returned an Exception.
– Diego Farias