Always going 'false' branch even if true?

A

Andy

Hi all,

I'm having a very weird problem. I have the following class..

using System;

namespace CCP.Core.Data {
public class Null {
private Null() {}

private static readonly string stringSurrogate = String.Empty;
private const short numberSurrogate = -1;
private const ushort ushortSurrogate = ushort.MaxValue;
private const uint uintSurrogate = uint.MaxValue;
private const ulong ulongSurrogate = ulong.MaxValue;

public static object GetSurrogate( Type ValueType ) {
object result;

result = null;

switch( ValueType.FullName.ToLower() ) {
case "system.string":
result = stringSurrogate;
break;
case "system.single":
case "system.double":
case "system.int16":
case "system.int32":
case "system.int64":
case "system.decimal":
result = numberSurrogate;
break;
case "system.uint16":
result = ushortSurrogate;
break;
case "system.uint32":
result = uintSurrogate;
break;
case "system.uint64":
result = ulongSurrogate;
break;
default:
result = null;
break;
}

return result;
}

public static object ValueToDatabase( object Value ) {
object result;
object surrogate;

surrogate = GetSurrogate( Value.GetType() );

result = surrogate == Value ? DBNull.Value : Value;

return result;
}

public static object ValueFromDatabase( object Value, Type TargetType
) {
object result;

result = Convert.IsDBNull( Value ) ? GetSurrogate( TargetType ) :
Value;

return result;
}
}
}

ValueFromDatabase works fine, but in my unit tests, ValueToDatabase is
not. Heres a sample test.

Assert.AreSame( DBNull.Value, Null.ValueToDatabase( Null.GetSurrogate(
typeof( short ) ) ), "Failed for short" );

Tracing through, its always returning Value instead of DBNull.Value,
even though I can debug and highlight the surrogate == Value and see
that it evaluates to true, it still picks the false expression.

Any ideas?

Thanks
Andy
 
S

Shardool Karnik

try

result = (surrogate.ToString() == Value.ToString()) ? DBNull.Value : Value;

object to object comparison is causing the problem for you ...
 
B

Bruce Wood

Why not

result = surrogate.Equals(Value) ? DBNull.Value : Value;

?

For objects, == is an identity comparison: it compares pointers. The
Equals() method compares the values of the objects where it is
overloaded to do so for particular types.
 
A

Andy

Ahh.. what was throwing me was that if i went to the immediate window
or did a quick watch on the expression, it was always evaluating to
true.

I'll try the Equals method.. thanks!

Andy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top