2

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?

2 Answers 2

3

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 "".

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thank you for clearing that up. I will have to look elsewhere then for potential problems.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.