I'm converting an old timed script from VB to C# and I need help with understanding what an If
statement's purpose is.
The code I need help with is:
... And If(cp.JobTitle, String.Empty) = String.Empty And ...
This is part of a SQL query and the cp.JobTitle
in the database is nullable string field.
Any help is appreciated!
CodePudding user response:
No, that is not part of a SQL query. Perhaps it's part of a LINQ query or some code that constructs a SQL query but there's nothing to do with SQL there.
Anyway, that VB code is using the If
operator with two operands. The equivalent of this VB:
If(cp.JobTitle, String.Empty) = String.Empty
is this C#:
(cp.JobTitle ?? string.Empty) == string.Empty
It's saying to use cp.JobTitle
unless it's Nothing
, in which case use String.Empty
. A better way to write functionally equivalent VB would be this:
String.IsNullOrEmpty(cp.JobTitle)
I hope the equivalent C# to that is obvious.
By the way, that VB code really ought to be using AndAlso
rather than And
. If you would use &&
in C# rather than &
, which pretty much everyone would, then you should be using AndAlso
in VB rather than And
. In both cases, you should only use the other if you explicitly don't want short-circuiting.