So I have this bit of code, if I break point on the return
statement the immediate window outputs the information below.
try
{
await connection.OpenAsync();
var obj = await cmd.ExecuteScalarAsync();
return obj != null ? Int32.Parse(obj.ToString()) != 1 : false;
}
catch (Exception ex)
{
Log.Error("An error has occurred checking a customer/product authorization.", ex);
return false;
}
finally
{
connection.Close();
}
Stored Procedure
Here is the relevant parts of the stored procedure. @HasAuthTable and @IsAuthorized are of the type bit
.
SELECT (CASE WHEN @HasAuthTable = 0 THEN 1 ELSE 0 END) | @IsAuthorized AS IsAuthorized
Immediate Window
obj
0
obj == null
false
obj != null
false
obj == 0
error CS0019: Operator '==' cannot be applied to operands of type 'object' and 'int'
obj != 0
error CS0019: Operator '!=' cannot be applied to operands of type 'object' and 'int'
(int)obj == 0
true
(int)obj != 0
false
obj.GetType().FullName
"System.Int32"
obj.Equals(null)
false
!obj.Equals(null)
true
Object.ReferenceEquals(obj, null)
false
!Object.ReferenceEquals(obj, null)
false
I've tried Rebuilding the solution didn't change anything. I have also tried restarting Visual Studio. No luck. Is this intended behavior? It seems like a bug.
Altered Stored Procedure
I tried changing the output of the stored procedure to match the following to see if it affects it in any way. The result is basically the same. static type of object
with the expected dynamic type, both having values but still returning false
for obj == null
and obj != null
.
SELECT CAST(((CASE WHEN @HasAuthTable = 0 THEN 1 ELSE 0 END) | @IsAuthorized) AS BIT) AS IsAuthorized
Respective Immediate Window
obj
false
obj != null
false
obj == null
false
obj.GetType().FullName
"System.Boolean"
You can't have an object set another object's reference to null like this without having them both aware of one another.
In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.
One way of avoiding returning null is using the Null Object pattern. Basically you return a special case object that implements the expected interface. Instead of returning null you can implement some kind of default behavior for the object. Returning a null object can be considered as returning a neutral value.
var obj = await cmd.ExecuteScalarAsync();
is doing Boxing.
Immediate Window displays incorrect value if 0 is boxed. It must be a bug in Immediate Window.
The picture is from Illustrated C# 2012 4th Edition by Daniel Solis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With