How/whether to use the `is` operator?

When reviewing a CAPI app recently, I saw C# syntax I’d never used or seen before:

my_var is true

From what I can tell, this is functionally equivalent to:

my_var == true

That raises a few questions:

  • Are the is and == operators equivalent in this type of use case?
  • Would there be a reason to prefer not using is?

Mea culpa: I didn’t Google before posting. Apart from laziness, I wasn’t sure if there were something special about Survey Solution’s usage of is that might make general C# answers on the internet wrong.

Note than if you define t1 with constant expression true and t2 with constant expression true you can write (t1==t2), but you can not write (t1 is t2) (you will get a syntax error).

You may want to check with the author of that questionnaire as to why he/she saw the use of is operator necessary in that particular case.

Instead of e.g. q1 is null you can write !IsAnswered(q1) to check if question q1 has been answered. As for the types (the other frequent use of the is operator) I can’t imagine you needing this as types in Survey Solutions are determined by the design of the questionnaire, unless you want to develop some expression that would allow some generality (untested):

((q1 is long) && (q1==6)) || ( (q1 is String) && (q1.ToLower()=="six"))

In practice we know for a particular questionnaire the type of q1 so can prune the branches of such an expression which will always be false.

1 Like