Casting - What is the difference between "(myObject) something" and "something like myObject" in C #?

I met this several times and was puzzled.

Cat c = new Cat("Fluffy"); return (Animal)c; Cat c = new Cat("Fluffy"); return c as Animal; 

What is the reason for the existence of both of these syntaxes?

+4
source share
4 answers

The as operator is safe. If the types are incompatible, as will return null .

An explicit cast, (Animal)c , on the other hand, will throw an InvalidCastException if the types are not compatible with the destination.

It is also worth noting that as only works for inheritance relationships, while an explicit casting operator will work for value types ...

 decimal d = 4.0m; int i = (int)d; 

... and any other explicit conversion operators defined in a type with public static explicit operator . They will not work with as .

+14
source

http://blogs.msdn.com/csharpfaq/archive/2004/03/12/88420.aspx

"Using the as operator differs from cast in C # in three important ways:

1) It returns null when the variable you are trying to convert does not belong to the requested type or inheritance chain instead of throwing an exception.

2) It can only be applied to variables of a reference type that are converted to reference types.

3) Use because it will not perform custom conversions, such as implicit or explicit conversion operators, that will perform casting syntax.

In fact, there are two completely different operations defined in IL that process these two keywords (castclass and isinst instructions) - it's not just “syntactic sugar” written by C # to get this different behavior. The as statement looks a little faster in versions 1.0 and v1.1 of the Microsoft CLR compared to casting (even in cases where there are no invalid throws that would significantly reduce casting efficiency due to exceptions).

+5
source

Wherein:

 return (Animal)c; 

You clearly say that c has the type of animal, and if not something went wrong.

Wherein:

 return c as Animal; 

You say that you are pretty sure that c has an animal type, but maybe not all the time.

Eric Lippert talks about this on his blog:

http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx

+2
source

Syntax cast, return (Animal)c; will throw an InvalidCastException if the object cannot be added to the type Animal . It is good if you know that this is an animal, and if it is not, something went wrong.

Syntax return c as Animal; returns null. This is useful if you want to avoid exceptions:

 Cat c = GetAnimal("Fluffy"); if (c == null) { AddAnimal("Fluffy"); } 
0
source

Source: https://habr.com/ru/post/1306697/


All Articles