Most of our development is done in vb.net (not my choice) and one frequently used code pattern uses an 'On Error GoTo' followed by a 'Resume Next' so that all database fields can be read with a DirectCast() and any DBNull values are just ignored.
The current code would be
On Error GoTo error_code
oObject.Name = DirectCast(oReader.Item("Name"), String)
oObject.Value = DirectCast(oReader.Item("Value"), Integer)
error_code:
Resume Next
C# code to replace this an enable the removal of the On Error code would be
oObject.Name = oReader["Name"] as string ?? string.Empty;
oObject.Value = oReader["Value"] as int? ?? -1;
The problem is that the vb.net eqivelent of this C# code uses a TryCast() which can only be used for reference types (nullable types are value types) whilst the C# as keyword can be used for reference and nullable types.
So in summary does anyone have an example of vb.net code that does the same thing as the C# code in a single line per database field?
-EDIT-
I've decided what I think is the best solution in our case. Helper methods would not be suitable (due to management) and we can't have extension methods as we're only using .NET 2.0 (though with VS 2008 so we get the If())
oObject.Name = If(oReader.IsDBNull(oReader.GetOrdinal("Name")), String.Empty, oReader.GetString(oReader.GetOrdinal("Name")))
oObject.Value = If(oReader.IsDBNull(oReader.GetOrdinal("Value")), 0, oReader.GetInt32(oReader.GetOrdinal("Value")))
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…