简体   繁体   中英

c# Object obj's value is {}. What is “{}”?

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

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

In case anyone comes across again this problem.

Solution if val object is shown {} in debug mode

// Check if its not null or empty
if (!IsNullOrEmpty(val.ToString().ToArray()))
{
    // Do something with val
    dt.Rows.Add(val);
}

public static bool IsNullOrEmpty<T>(T[] array)
{
    return array == null || array.Length == 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM