Hello. 1
The next interview question we're going to discuss is "What is the difference between "is" and "as" keywords?" 2
The "is" keyword is used to check if an object is of a given type. 3
It returns a Boolean as a result. 4
In this case, the result will be true because the text variable is a string. We can use the "is" keyword 5
with value types and reference types as well. 6
In this case, the result will be false because the text variable is not an integer. The "is" keyword 7
is most often used to ensure that a type can be safely cast to some other type. 8
We can also have some business logic driven by the type of some variable. 9
In the case of type A, we want to execute different logic 10
then in the case of type B. The "as" keyword is used to cast a variable to a given type. 11
Here I am casting an object to a string. 12
The cast will be successful and the result will be the string "Hello!". 13
If the cast would not be successful, the result would be null. 14
As you can see, the first variable has a value. 15
But the second is null. 16
The fact that in the case of invalid casting, the result will be null is the crucial difference between 17
casting with "as" keyword and regular casting with parentheses. 18
Regular casting throws an exception when the cast fails. 19
Let's see this in code. 20
This cast simply returned a null, but this caused InvalidCastException. Because casting with "as" can 21
return null 22
it can only be used with nullable types, so all reference types plus nullable value types. 23
It's not valid with the non-nullable value types. 24
This doesn't work because when casting fails (and it will in this case), we will try to assign null to 25
an integer which is not legal in C# because integer is a non-nullable value type. 26
Let's summarize. The "is" keyword checks 27
if the object is of a given type. It returns a boolean result. The "as" keyword casts an object 28
to a given type. 29
It can only be used for casting to reference types or nullable value types. 30
During the interview, you might be asked "What is the difference between regular cast and casting with 31
"as" keyword?" 32
Well, if casting with "as" fails, the result will simply be null. 33
When 34
regular casting fails an InvalidCastException will be thrown. 35
Another question you can hear is "Why can we only use the "as" keyword to cast objects to nullable types?" 36
Because if casting with "as" fails, null will be returned. Null can only be assigned to nullable types. 37
All right, that's it about the "is" and "as" keywords. 38
Thanks for watching, and I'll see you in the next lecture.