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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With