The is keyword and its result

Matthieu

Member
Joined
Aug 15, 2020
Messages
23
Programming Experience
Beginner
Hi everyone,

I started learning C# and got totaly confused by the behaviour of the is keyword.
I understand that in the example below the value for b will be true:

C#:
int number = 10;
bool b = number is int;

In underneath example the value for for b will be false:
C#:
int number = 10;
bool b = number is 20

Somewhat logical because 10 != 20, but I thought the is keywords checks if something is of specific type and not of the same value. In other words, I expected b to be true because the literal value 20 is just also an int.

Thanks for the help!
 
What are your expectations with these?
C#:
            string s = "str";
            bool bl = s is string;
C#:
            string s = "str";
            bool bl = s is "str";

I think you may be misunderstanding is : is - C# Reference

  • Type pattern, which tests whether an expression can be converted to a specified type and, if it can be, casts it to a variable of that type.
  • Constant pattern, which tests whether an expression evaluates to a specified constant value.
  • var pattern, a match that always succeeds and binds the value of an expression to a new local variable.
 
Back
Top Bottom