I’m using some old code that runs a sql query as a reference.
At some point, it gets to something like:
sqlDataAdapter.Fill(dataSet); DataRow dataRow = dataSet.Tables[0].Rows[0]; Object obj = dataRow[fieldName];
The old code does:
string output; if (!string.IsNullOrEmpty(obj.ToString())) { output = obj.ToString(); } else { output = "Not Available"; }
I changed them to:
output = obj as string ?? "Not Available"
But sometimes, it broke. As I suspected, it was happening breaking when the entry was an int
. Casting as an int
in those cases solved that problem.
Then another problem arose when there was no entry for obj[fieldName]
of type int. When I stepped through the debugger, I was surprised to find that obj
wasn’t null
. In VS, mousing over revealed it had a value {}
.
What the heck is {}
? How do I make a boolean test of it?
(In the old code, it appears .ToString()
returns ""
in this case and works as expected.)
Advertisement
Answer
{
and }
are opening and closing braces and symbolic of the start and finish of an object. Hence an empty object with no special properties is depicted in shorthand as {}
. The debugger uses this notation to help you visually distinguish between an empty object, an empty string and null.
If you hover over obj[fieldName]
and there is no entry for fieldName
, the debugger won’t care about that, it’ll show the value of obj
. You’ll have to use the immediate window or a watch/quickwatch. The debugger will only see you hovering over obj and assume you’re referring to the array itself, not the contents of the array at the specified index.