CollectionBase InnerList with Arrays

A

adriaandavel

Hi all,

I am trying to use a collection of String Arrays in an inherited
instance of CollectionBase, but the InnerList.IndexOf does not seem to
work, any ideas?

My code is:

public void Add(string str1, string str2, string str3)
{
string[] Detail = new string[3] { str1, str2, str3};
this.InnerList.Add(Detail);
}

public int ArrayPosition(string str1, string str2, string str3)
{
string[] Detail = new string[3] { str1, str2, str3};
return InnerList.IndexOf(Detail);
}

The Add() works fine, and in the debugger I can see all the Arrays I've
added, but the ArrayPosition() always returns -1...
 
M

Marc Gravell

That is because you are creating a new array, and the list is likely using
referential comparison on the array reference. You would need to use a
comparer that looked inside the array.

This is essentially ths same as the following, which prints "false" 3
times - because the arrays just are not connsidered "equal" by default:

string[] a = { "a", "b", "c" };
string[] b = { "a", "b", "c" };
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));
Console.WriteLine(Array.Equals(a,b));

Marc
 
D

Dustin Campbell

I am trying to use a collection of String Arrays in an inherited
instance of CollectionBase, but the InnerList.IndexOf does not seem to
work, any ideas?

My code is:

public void Add(string str1, string str2, string str3)
{
string[] Detail = new string[3] { str1, str2, str3};
this.InnerList.Add(Detail);
}
public int ArrayPosition(string str1, string str2, string str3)
{
string[] Detail = new string[3] { str1, str2, str3};
return InnerList.IndexOf(Detail);
}
The Add() works fine, and in the debugger I can see all the Arrays
I've added, but the ArrayPosition() always returns -1...

BTW (this is a little OT), you should use the "List" property instead of
"InnerList" inside of a CollectionBase descendent. If you don't use List,
known of the protected methods that you can override will be called (e.g.
OnInsert, OnRemove, OnValidate).

Best Regards,
Dustin Campbell
Developer Express Inc.
 

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