Public Function DBToID(ByVal strValue As Object) As Integer
If strValue Is DBNull.Value Then Return -1
If strValue = "-1" Then Return -1
Return CInteger(strValue)
End Function
I am trying to convert this code in C# and I did this
public static int DBToID(object strValue)
{
if (object.ReferenceEquals(strValue, DBNull.Value))
return -1;
if (object.ReferenceEquals(strValue,"-1"))
return -1;
return CInteger(strValue.ToString());
}
I just need to know whether I am doing it right or not as before I was doing
public static int DBToID(object strValue)
{
if (object.ReferenceEquals(strValue, DBNull.Value))
return -1;
if (strValue == "-1")
return -1;
return CInteger(strValue.ToString());
}
but it is saying Possible unintended reference comparison it is not giving any error just a green line under strValue=="-1".So please explain that object.referenceequals is correct or not .Thanks in advance
public int DBToID(object strValue)
{
if (strValue == DBNull.Value || Convert.ToString(strValue) == "-1")
return -1;
return Convert.ToInt32(strValue);
}
Try this
In C#, when the first operand of the == operator is cast as a reference-type (without any operator-overloading) then the == operator maps to the Object.ReferenceEquals operation. For the string-equality operation to be performed both operands must be known at compile-time to be String instances.
The most succinct (and safe) conversion would be this:
public Int32 DbToId(Object value) {
Int32 ret;
return value == DBNull.Value ? -1 :
Int32.TryParse( CultureInfo.InvariantCulture, value, out ret ) ? ret :
-1;
}
...which is a shorter form of this:
public Int32 DbToId(Object value) {
if( Object.ReferenceEquals( value, DBNull.Value ) ) return -1;
Int32 ret;
if( Int32.TryParse( CultureInfo.InvariantCulture, value, out ret ) ) return ret;
return -1; // fallback, base-case
}
Generally, try to avoid using VB.NET functions in C# (like CInteger) or the Convert.ToXXX methods as it is not immediately obvious what or how the conversion will work. Also avoid ToString calls with no arguments for the same reason. Prefer TryParse with appropriate IFormatInfo overloads.
When the == operator is used to compare two strings, the Equals method is called, which checks for the equality of the contents of the strings rather than the references themselves. For instance, "hello".Substring(0, 4)=="hell" is true, even though the references on the two sides of the operator are different (they refer to two different string objects, which both contain the same character sequence).
Note that operator overloading only works here if both sides of the operator are string expressions at compile time - operators aren't applied polymorphically. If either side of the operator is of type object as far as the compiler is concerned, the normal == operator will be applied, and simple reference equality will be tested.
Taken from here
The code you've written is not wrong per se. The linked post/snippet should help with any confusion for how strings work. Unless you know what you are doing explicitly, using ReferenceEquals is a bad idea and I would use one of the other by-value check methods.
If you call '.ToString()' on the object, then your second condition should work fine:
public int DBToID(object strValue)
{
if (strValue == DBNull.Value)
return -1;
if (strValue.ToString() == "-1")
return -1;
return System.Convert.ToInt32(strValue);
}
Related
This pattern comes up very frequently in my code:
x= x== 0? 1: x;
//or
x= x==null? 1: x;
However it happens that sometimes x is a long expression and I'd have to use intermediate variables. That's just useless boilerplate code. I can cook up a method and call it instead:
Util.IfNullOrZero(x, 1);
But that's just ugly. What is the best way of expressing the pattern? In ruby there is such syntax for when x is nil which gets rid of redundant x's:
x||= 1
I could extend object in a manner
public static class wtf
{
public static T Default<T>(this object o, T d)
{
return o == null ? d : new object[] { o }.Cast<T>().First();
}
}
And then do
object param= null;
int x= param.Default(1);
But that's a bit expensive.
In short how to best make C# do x||= 1 like in ruby?
Update
This is what I cooked up. I'm currently looking for a faster way of using the Template parameter to convert object to T.
public static class MyExtensions
{
public static T d<T>(this object o, T d)
{
return o == null || o.Equals(default(T)) ? d : new object[] { o }.Cast<T>().First();
}
}
In fact the code does three things at once: Casts to default type, checks for default value and also checks for null.
Update 2
return o == null || o.Equals(default(T)) ? d : (T)o; // much simpler and faster
I still think it is a commonality which needs to be included in core language.
Update 3
This is what I finally wrote, taking into account DataTable DBNull types.
public static T d<T>(this object o, T d)
{
return o == null || (o is System.DBNull) || o.Equals(default(T)) ? d : (T)Convert.ChangeType(o, typeof(T));
}
For handling the "==null" case, the null coalesce operator does the trick.
y = x ?? z;
means
if (x == null)
y = z;
else
y = x;
I'm not aware of something that check for both zero and null, writing a method to perform this task might be the best solution. Here it goes:
public static T IsNullOrZero<T>(this T variable, T defaultValue)
{
// defaultValue can't be null, doesn't make sense
if (defaultValue == null) throw new ArgumentException("default value can't be null", "defaultValue");
if (variable == null || variable.Equals(default(T)))
return defaultValue;
return variable;
}
Usage:
x = x.IsNullOrZero(y);
Note: this in fact works on non-numbers too (name might be misleading if dealing with non-numbers... maybe something along the lines of IsNullOrDefault might be a better name).
You can check like
public static bool IsNullOrValue(this int? value, int valueToCheck)
{
return (value??valueToCheck) == valueToCheck;
}
more on here
For checking for null and providing a default value, you can use the ?? operator:
return x ?? new Foo();
That means, if x is null, return new Foo(), else return x. You can use it for reference types and nullable types. For nun-nullable types like int, you still need to explicitly check for 0.
What you want is the Coalesce operator (??), which does just that - if returns the first operand if it's not null, and the second if it is. This will instantiate a new object if the current one is null:
return myObj ?? new MyObject();
Note that the ?? operator works only for classes and reference types, not for ints and other value types that can't be null. There, you'll have to check manually for default, uninitialized values (0 for ints and shorts and stuff, false for bools, and so forth)
I'm trying to compare a double value to see if it is equal to zero. The following will work:
Assert.IsTrue(0d==0);
However this will fail:
Assert.IsTrue(Equals(0d,0));
I think the second argument (0) is being treated as an integer. However, I don't understand why Equals(0d, 0) evaluates as false whereas 0d==0 is true. It can't be rounding because both values are directly input as zeros.
Intuitively it's as easy as "they're not both doubles".
If you want to go in depth however, Object.Equals (the static method you call in your second example) is this:
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool Equals(object objA, object objB)
{
return ((objA == objB) || (((objA != null) && (objB != null)) && objA.Equals(objB)));
}
The 2 references are not equal, neither is null, so Double.Equals gets called virtually:
public override bool Equals(object obj)
{
if (!(obj is double))
{
return false;
}
double d = (double) obj;
return ((d == this) || (IsNaN(d) && IsNaN(this)));
}
The argument is not a double so it returns false.
This is taken from mscorlib for .NET 4.0 64-bit.
I believe Equals(0d,0) may be doing a type comparison also. 0d is not technically equal to 0 because they are not same type.
Edit:
http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx
This is the case it seems.
MSDN: true if the specified Object is equal to the current Object; otherwise, false.
Alternatively you could to something like Convert.ToDouble(0) and it should work. I'm not near a C# compiler right now so I can't check if that's correct.
In the first line the == operator casts the values to a common type, while in the second the Double.Equals method is called as a result, and it before comparing does a type-check which returns false, as one value is a double and the other is an integer.
While browsing the MSDN documentations on Equals overrides, one point grabbed my attention.
On the examples of this specific page, some null checks are made, and the objects are casted to the System.Object type when doing the comparison :
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
Is there a specific reason to use this cast, or is it just some "useless" code forgotten in this example ?
It is possible for a type to overload the == operator. The cast to object ensures that the original definition is used.
As others said, the type might override the == operator. Therefore, casting to Objectis equivalent to if (Object.ReferenceEquals(p, null)) { ... }.
I believe casting to System.Object would get you around any operator overloading that TwoDPoint might have.
It likely exists to avoid confusion with an overloaded == operator. Imagine if the cast did not exist and the == operator was overloaded. Now the p == null line would potentially bind to the operator ==. Many implementations of operator == simply defer to the overridden Equals method. This could easily cause a stack overflow situation
public static bool operator==(TwoDPoint left, TwoDPoint right) {
return left.Equals(right);
}
public override bool Equals(System.Object obj) {
...
TwoDPoint p = obj as TwoDPoint;
if ( p == null ) { // Stack overflow!!!
return false;
}
...
}
By casting to Object the author ensures a simple reference check for null will occur (which is what is intended).
This might have been part of a larger sample where the == operator was overloaded. In that case, using obj == null could have resulted in StackOverflow if TwoDPoint.Equals(object) was invoked as part of the == definition.
I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data.
Here is the code :
if (region != null)
{
....
}
This is working but when looping and looping sometime the region object is NOT null (I can see data inside it in debug mode). In step-by-step when debugging, it doesn't go inside the IF statement... When I do a Quick Watch with these following expression : I see the (region == null) return false, AND (region != null) return false too... why and how?
Update
Someone point out that the object was == and != overloaded:
public static bool operator ==(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
public static bool operator !=(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) != 0 || r1.Id != r2.Id);
}
Is the == and/or != operator overloaded for the region object's class?
Now that you've posted the code for the overloads:
The overloads should probably look like the following (code taken from postings made by Jon Skeet and Philip Rieck):
public static bool operator ==(Region r1, Region r2)
{
if (object.ReferenceEquals( r1, r2)) {
// handles if both are null as well as object identity
return true;
}
if ((object)r1 == null || (object)r2 == null)
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
public static bool operator !=(Region r1, Region r2)
{
return !(r1 == r2);
}
Those operator overloads are broken.
Firstly, it makes life a lot easier if != is implemented by just calling == and inverting the result.
Secondly, before the nullity checks in == there should be:
if (object.ReferenceEquals(r1, r2))
{
return true;
}
Both of the overloads are incorrect
public static bool operator ==(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
if r1 And r2 are null, the first test (object.ReferenceEquals(r1, null)) will return false, even though r2 is also null.
try
//ifs expanded a bit for readability
public static bool operator ==(Region r1, Region r2)
{
if( (object)r1 == null && (object)r2 == null)
{
return true;
}
if( (object)r1 == null || (object)r2 == null)
{
return false;
}
//btw - a quick shortcut here is also object.ReferenceEquals(r1, r2)
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
This can sometimes happen when you have multiple threads working with the same data. If this is the case, you can use a lock to prevent them from messing with eachother.
For equality comparison of a type "T", overload these methods:
int GetHashCode() //Overrides Object.GetHashCode
bool Equals(object other) //Overrides Object.Equals; would correspond to IEquatable, if such an interface existed
bool Equals(T other) //Implements IEquatable<T>; do this for each T you want to compare to
static bool operator ==(T x, T y)
static bool operator !=(T x, T y)
Your type-specific comparison code should be done in one place: the type-safe IEquatable<T> interface method Equals(T other).
If you're comparing to another type (T2), implement IEquatable<T2> as well, and put the field comparison code for that type in Equals(T2 other).
All overloaded methods and operators should forward the equality comparison task to the main type-safe Equals(T other) instance method, such that an clean dependency hierarchy is maintained and stricter guarantees are introduced at each level to eliminate redundancy and unessential complexity.
bool Equals(object other)
{
if (other is T) //replicate this for each IEquatable<T2>, IEquatable<T3>, etc. you may implement
return Equals( (T)other) ); //forward to IEquatable<T> implementation
return false; //other is null or cannot be compared to this instance; therefore it is not equal
}
bool Equals(T other)
{
if ((object)other == null) //cast to object for reference equality comparison, or use object.ReferenceEquals
return false;
//if ((object)other == this) //possible performance boost, ONLY if object instance is frequently compared to itself! otherwise it's just an extra useless check
//return true;
return field1.Equals( other.field1 ) &&
field2.Equals( other.field2 ); //compare type fields to determine equality
}
public static bool operator ==( T x, T y )
{
if ((object)x != null) //cast to object for reference equality comparison, or use object.ReferenceEquals
return x.Equals( y ); //forward to type-safe Equals on non-null instance x
if ((object)y != null)
return false; //x was null, y is not null
return true; //both null
}
public static bool operator !=( T x, T y )
{
if ((object)x != null)
return !x.Equals( y ); //forward to type-safe Equals on non-null instance x
if ((object)y != null)
return true; //x was null, y is not null
return false; //both null
}
Discussion:
The preceding implementation centralizes the type-specific (i.e. field equality) comparison to the end of the IEquatable<T> implementation for the type.
The == and != operators have a parallel but opposite implementation. I prefer this over having one reference the other, such that there is an extra method call for the dependent one. If the != operator is simply going to call the == operator, rather than offer an equally performing operator, then you may as well just use !(obj1 == obj2) and avoid the extra method call.
The comparison-to-self is left out from the equals operator and the IEquatable<T> implementations, because it can introduce 1. unnecessary overhead in some cases, and/or 2. inconsistent performance depending on how often an instance is compared to itself vs other instances.
An alternative I don't like, but should mention, is to reverse this setup, centralizing the type-specific equality code in the equality operator instead and have the Equals methods depend on that. One could then use the shortcut of ReferenceEquals(obj1,obj2) to check for reference equality and null equality simultaneously as Philip mentioned in an earlier post, but that idea is misleading. It seems like you're killing two birds with one stone, but your actually creating more work -- after determining the objects are neither both null nor the same instance, you will then, in addition, STILL have to on to check whether each instance is null. In my implementation, you check for any single instance being null exactly once. By the time the Equals instance method is called, it's already ruled out that the first object being compared is null, so all that's left to do is check whether the other is null. So after at most two comparisons, we jump directly into the field checking, no matter which method we use (Equals(object),Equals(T),==,!=). Also, as I mentioned, if you really are comparing and object to itself the majority of the time, then you could add that check in the Equals method just before diving into the field comparisons. The point in adding it last is that you can still maintain the flow/dependency hierarchy without introducing a redundant/useless check at every level.
So is it that these checks here are not right:
public static bool operator !=(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
...
There's another possibility that you need to click the refresh icon next to the parameter that you're watching. VS try to keep up with the performance while not evaluating every statement/parameter. Take a look to make sure, before you start making changes to places that's non relevant.
bool comp;
if (object.IsNullOrEmpty(r1))
{
comp = false;
}
if (object.IsNullOrEmpty(r2))
{
comp = false;
}
return comp;
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I check for nulls in an '==' operator overload without infinite recursion?
When I overload the == operator for objects I typically write something like this:
public static bool operator ==(MyObject uq1, MyObject uq2) {
if (((object)uq1 == null) || ((object)uq2 == null)) return false;
return uq1.Field1 == uq2.Field1 && uq1.Field2 == uq2.Field2;
}
If you don't down-cast to object the function recurses into itself but I have to wonder if there isn't a better way?
As Microsoft says,
A common error in overloads of
operator == is to use (a == b), (a ==
null), or (b == null) to check for
reference equality. This instead
results in a call to the overloaded
operator ==, causing an infinite loop.
Use ReferenceEquals or cast the type
to Object, to avoid the loop.
So use ReferenceEquals(a, null) || ReferenceEquals(b, null) is one possibility, but casting to object is just as good (is actually equivalent, I believe).
So yes, it seems there should be a better way, but the method you use is the one recommended.
However, as has been pointed out, you really SHOULD override Equals as well when overriding ==. With LINQ providers being written in different languages and doing expression resolution at runtime, who knows when you'll be bit by not doing it even if you own all the code yourself.
ReferenceEquals(object obj1, object obj2)
#neouser99: That's the right solution, however the part that is missed is that when overriding the equality operator (the operator ==) you should also override the Equals function and simply make the operator call the function. Not all .NET languages support operator overloading, hence the reason for overriding the Equals function.
if ((object)uq1 == null)
return ((object)uq2 == null)
else if ((object)uq2 == null)
return false;
else
//return normal comparison
This compares them as equal when both are null.
Just use Resharper to create you Equals & GetHashCode methods. It creates the most comprehensive code for this purpose.
Update
I didn't post it on purpose - I prefer people to use Resharper's function instead of copy-pasting, because the code changes from class to class. As for developing C# without Resharper - I don't understand how you live, man.
Anyway, here is the code for a simple class (Generated by Resharper 3.0, the older version - I have 4.0 at work, I don't currently remember if it creates identical code)
public class Foo : IEquatable<Foo>
{
public static bool operator !=(Foo foo1, Foo foo2)
{
return !Equals(foo1, foo2);
}
public static bool operator ==(Foo foo1, Foo foo2)
{
return Equals(foo1, foo2);
}
public bool Equals(Foo foo)
{
if (foo == null) return false;
return y == foo.y && x == foo.x;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
return Equals(obj as Foo);
}
public override int GetHashCode()
{
return y + 29*x;
}
private int y;
private int x;
}
But why don't you create an object member function? It can certainly not be called on a Null reference, so you're sure the first argument is not Null.
Indeed, you lose the symmetricity of a binary operator, but still...
(note on Purfideas' answer: Null might equal Null if needed as a sentinel value of an array)
Also think of the semantics of your == function: sometimes you really want to be able to choose whether you test for
Identity (points to same object)
Value Equality
Equivalence ( e.g. 1.000001 is equivalent to .9999999 )
Follow the DB treatment:
null == <anything> is always false