What does this syntax do? if (obj - SomeType obj2)

I am starting to see these statements, and I am trying to wrap my head in these statements.

if (obj is SomeAuto car) { //Do stuff } 

If I understand correctly, we basically throw obj into a variable machine, which would be a type of "SomeAuto"?

1) What is the official terminology of this statement?

2) What happens if I want to change the if statement to conditionally execute for a specific reason?

For example, SomeAuto is a base class, and I need only a certain type of car, or I want all SomeAuto, except, perhaps, one specific type.

+5
source share
1 answer

This if statement uses the is expression added in C # 7.0 when matching with a pattern . Documents indicate that:

This template expression extends the familiar operator to query an object beyond its type.

It allows you to check whether the obj type has a specific type, and also assigns the cast result to a variable.


Before this function, you probably write:

 var car = obj as SomeAuto; if(car != null) { //Do Stuff } 

As @BurnBA pointed out, the difference when using as than the original is is that Note that the as operator only performs reference conversions that are convertible along the transform axes and convert to box and therefore cannot be used to check types of values โ€‹โ€‹that don't allow zero value.

+6
source

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


All Articles