Array.IndexOf and structures

Z

Zanna

Hi all!

Problem: let's say I have a structure

Public Structure MyObject

Public Id As String

Public Description As String

Public Overrides Function Equals(ByVal obj As Object) As Boolean

If TypeOf obj Is String Then

Return DirectCast(obj, String).Equals(Me.Id)

Else

Return DirectCast(obj, Deposito).Id.Equals(Me.Id)

End If

End Function

End Structure

Now, have an array of MyObject:

Dim myObj(3) As MyObject

I fill the array and then I do

Dim idx As Int32 = Array.IndexOf(myObj, "MyId", 0, myObj.Length)

This last line give to me always -1, but I'm sure that the Equals() works.
MSDN says that the Array.IndexOf works on the override of Object.Equals(),
so I really don't know why this does not works for me :)

Some help?
 
M

Marius Bucur

Hi,
change MyObject declaration to be a class instead of a structure. If the
program works than is a boxing problem. Structures are recommended for
immutable types.
Marius
 
Z

Zanna

Marius Bucur said:
change MyObject declaration to be a class instead of a structure. If the
program works than is a boxing problem. Structures are recommended for
immutable types.

mmm... But the ToString() works i.e. I add the structure to a listbox...

I'd like to use a structure because it would be faster for few data.
 
M

Marius Bucur

ValueType[] arrays contain references to boxed valuetypes elements.
Consider the following code
struct MyStruct
{
public string id;
}

....
void foo()
{
MyStruct[] ar = new MyStruct[10];
ar[0].id = "Test";

MyStruct val = ar[0]; //unboxing is perform
val.id = "NewValue";
//now ar[0].id == "Test" and val.id = "NewValue"
//you want to modify the element in the collection you must either use
// ar[0].ID = "NewValue" (in this case unboxing is not performed) or put
the new value in
//the collection ar[0] = val'
}

I don't think that in a situation like this if you use a struct instead of a
class your code will be faster, consider making a test.

Struct Usage Guidelines (cat from msdn)
It is recommended that you use a struct for types that meet any of the
following criteria:
- Act like primitive types.
- Have an instance size under 16 bytes.
- Are immutable.
- Value semantics are desirable.

Marius
 

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