简体   繁体   中英

generic list of objects contains short returning false

I am working on a project and i have to check for some values of type short in a generic list of object. Strangely I noticed that it is always returning false even if there is that value in the generic list of objects. I am providing a small piece of code which replicates that scenario in my project.

List<object> objectList = new List<object>();
objectList.Add(1);
objectList.Add(2);
objectList.Add(3);
if (objectList.Contains(1))
{
    short i = 1;
    if (objectList.Contains(i))
    {
    }
    else if (objectList.Contains(i.ToString()))
    {
    }
    else
    {
        //Entering this else this loop only
    }
}

My assumption is because of the difference in the size for those types it may be returning false. Any other thoughts.

Thanks.

objectList.Add(1);

is the same as

int i = 1;
objectList.Add(i);

So

int y = 1;
objectList.Contains(y); // true

short z = 1;
objectList.Contains(z); // false

You are adding boxed Integer objects to the list, then seeing if a boxed short or string version of the number is in the list, both of which are going to be false because they're different types.

Try casting your short to an int in the first test. Why did you choose to not use generic <int> and skip the boxing/unboxing?

short is an object type so by default it would only be equal to it's own instance. This equality has been overriden inside the framework as such:

public override bool Equals(object obj)
{
  if (!(obj is short))
    return false;
  else
    return (int) this == (int) (short) obj;
}

Not how you and me would have expected it:)

It is even more unexpected than you would think. Take the following cases:

int i = 1;
short s = 1;
System.Console.WriteLine(i==s ? "Yes" : "No"); // Yes
System.Console.WriteLine(i.CompareTo(s)==0 ? "Yes" : "No"); // Yes
System.Console.WriteLine(s.CompareTo(i) == 0 ? "Yes" : "No"); // ERROR !
System.Console.WriteLine(s.Equals(i) ? "Yes" : "No"); // No
System.Console.WriteLine(i.Equals(s) ? "Yes" : "No"); // Yes

Not very consistent en predicatable

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