TheIronCheek
TheIronCheek

Reputation: 1149

Protecting Variable From Null Value

I have some old code that I'm running through to make sure it's as stable as possible. Once in a blue moon, something breaks and leaves a bunch of garbage data in the database so I'm going through to see where a potential error could occur. I've found a bunch of variable assignments that look something like this:

myVariable = dr.Item("myItem") & ""

If dr.Item("myItem") resolves to Null, would the & "" protect myVariable from being Null and set it to "" or would the Null cause me problems?

Upvotes: 2

Views: 176

Answers (2)

Fabio
Fabio

Reputation: 32445

You don't need & operator and extra instance of type String, which concatenate operator will create.
Use .ToString() method

dr.Item("myItem").ToString()

DataRow.Item property return instance of type Object. Then calling ToString() method of that instance will return what you expected in your case (Item contain value of type String)

If item contains DbNull value, then empty string will be returned

DBNull.ToString Method

Or use extension method .Field(Of T)

dr.Field(Of String)("myItem")

DataRowExtensions.Field(Of T) Method (DataRow, String)

If column doesn't exist then Column not in the table Exception will be thrown

Upvotes: 0

James Thorpe
James Thorpe

Reputation: 32212

You're guaranteed to get a string back, whether dr.Item("myItem") is a string, Nothing or DBNull.Value. As per the documentation for the & Operator:

The data type of result is String. If one or both expressions evaluate to Nothing or have a value of DBNull.Value, they are treated as a string with a value of "".

Upvotes: 3

Related Questions