Differences in evaluation between IF statement and If, then, else

I came across a script that I did not expect, and I need help. Our current system makes calls to SQL-stored processes and as such creates SQL commands, adds parameters, and adds the values ​​of these parameters ... say, for insertion.

We had code like the one below ...

cmd.Parameters.Add("@MyTimestamp", SqlDbType.DateTime)
If MyObject.MyTimestamp <> Nothing Then
   cmd.Parameters.Item("@MyTimestamp").Value = MyObject.MyTimestamp
Else
   cmd.Parameters.Item("@MyTimestamp").Value = Nothing
End If

Now, when I first saw this, I was a little surprised that MyObject.MyTimestamp had ever evaluated Nothing, but it had been there for years without any problems. During an attempt to clear the code to add a parameter and set its value, it was combined and, as such, the code above ...

cmd.Parameters.Add("@MyTimestamp", SqlDbType.DateTime).Value = If(MyObject.MyTimestamp <> Nothing, MyObject.MyTimestamp, Nothing)

For me, it looked similar to what the code originally did, however this is not what was discovered during testing. During testing, I received a SqlTypeException:

SqlDateTime. 1/1/1753 12:00:00 AM 12/31/9999 11:59:59 PM.

, If MyObject.MyTimestamp Nothing, , DateTime.MinValue, sql, . , , Nothing ( , /), . , , ...?

+4
1

( ), Nothing null #, Default(T), , MyObject.MyTimestamp:

MyObject.MyTimestamp <> Nothing

, - (DateTime.MinValue), , -, .

, :

If(MyObject.MyTimestamp <> Nothing, MyObject.MyTimestamp, Nothing)

(MyObject.MyTimestamp, Nothing) , , , MyObject.Timestamp datetime, datetime .

, :

If MyObject.MyTimestamp <> Nothing Then
   cmd.Parameters.Item("@MyTimestamp").Value = MyObject.MyTimestamp
Else
   cmd.Parameters.Item("@MyTimestamp").Value = Nothing
End If

, "@MyTimestamp" SqlDbType.DateTime, . , DbNull , , .

, , DbNull.Value, Nothing:

If MyObject.MyTimestamp <> Nothing Then
   cmd.Parameters.Item("@MyTimestamp").Value = MyObject.MyTimestamp
Else
   cmd.Parameters.Item("@MyTimestamp").Value = DbNull.Value
End If
+3

All Articles