0

This method doesn't work at all:

    public static void Delete(ref Prot[] pack, Prot prot)
    {
        var temp = new List<Prot>(pack);
        temp.Remove(prot);
        pack = temp.ToArray();
    }

What am I doing wrong?

Thank you.

1 Answers1

4

Your class Prot needs to override the Object.Equals() method. This is how List<T>.Remove works. From the documentation:

If type T implements the IEquatable<T> generic interface, the equality comparer is the Equals method of that interface; otherwise, the default equality comparer is Object.Equals.

If you don't override Object.Equals it will just use the default implementation which checks for reference equality, not value equality.

So, temp.Remove(prot); was never removing any values. (This can be validated based on the return value of Remove. It returns true if it successfully removes a value, and false otherwise.

Here's a basic example: http://ideone.com/vOZoYI


Initial Answer (issue was a typo in question).

You are modifying a new object, a List<Prot>, not the Prot[] parameter. If you assign pack to the List<Prot>.ToArray() then it will remove it from the array passed in.

public static void Delete(ref Prot[] pack, Prot prot)
{
    var temp = new List<Prot>(pack);
    temp.Remove(prot);
    pack = temp.ToArray();
}
clcto
  • 9,530
  • 20
  • 42
  • Sorry about that, It's just misspelling. It still doesn't work. – user3149474 Jan 08 '14 at 17:47
  • It seems strange to me. In that object I've got just two int fields, so if they are equal to same fields of other object, objects are equal by default. Or isn't? – user3149474 Jan 08 '14 at 18:19
  • @user3149474 No. The default `Equals` implementation is reference equality, that is, both sides refer to the same object. `Object a, b; a = new Object(); b = a; // a.Equals(b) -> true` but `a = new Object(); b = new Object(); // a.Equals(b) -> false` since both `a` and `b` refer to different objects. – clcto Jan 08 '14 at 18:53