Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

I'm starting to see these statements and I am trying to wrap my head around these kind of statements.

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

If I understand correctly we basically are casting obj into the variable car which would be a type "SomeAuto"?

1) What is the official terminology of this statement?

2) What would happen if I wanted to change the if statement to conditionally execute for a particular reason?

For example say SomeAuto is a base class and I only wanted a certain type of auto, or say I want all of the SomeAuto except maybe one particular kind.

like image 607
John Doe Avatar asked Oct 13 '17 14:10

John Doe


1 Answers

This if statement is using the is expression added in C# 7.0 under pattern matching. Docs specify that:

The is pattern expression extends the familiar is operator to query an object beyond its type.

It enables you to check if obj is of a specific type and also assigns the casted result into a variable.


Before these feature you'd probably write:

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

As pointed out by @BurnBA a difference when using the as than the original is is that Note that the as operator performs only reference conversions, nullable conversions, and boxing conversion and therefore cannot be used to check non-nullable value types.

like image 187
Gilad Green Avatar answered Nov 11 '22 04:11

Gilad Green