Why can I get the index of the item of the array when I use string*, but can not get the index of t

A

Allen Maki

Why can I get the index of the item of the array when I use string*, but
can not get the index of the array when I use any other type (such as
Int32)?

This code will compile perfectly, but if I replace String* with Int32, the
code would not compile?

The code using String* type:

#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;
using namespace System::Collections;

int _tmain()
{
String* Items[] = { S"Dog", S"Cat", S"Elephant", S"Gerbil", S"Dog",
S"Horse", S"Pig", S"Cat" };
String* Item = S"Elephant";
int pos = Array::IndexOf(Items, Item);
Console::WriteLine(S"Index of Item in Items is {0}", __box(pos));
return 0;
}

The code using Int32

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;
using namespace System::Collections;

int _tmain()
{
Int32 Items [] = {1,3,5,7,4,9,6};
Int32 Item = 7;
int pos = Array::IndexOf(Items, Item);
Console::WriteLine(S"Index of Item in Items is {0}", __box(pos));

return 0;
}
 
B

Bruno van Dooren

The code using Int32
#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;
using namespace System::Collections;

int _tmain()
{
Int32 Items [] = {1,3,5,7,4,9,6};
Int32 Item = 7;
int pos = Array::IndexOf(Items, Item);
Console::WriteLine(S"Index of Item in Items is {0}", __box(pos));

return 0;
}

Hi,

This does not compile on my machine.
However, when I change this
int pos = Array::IndexOf(Items, Item);
to this:
int pos = Array::IndexOf(Items, __box(Item));

it compiles cleanly and it also prints the correct index (3).
IndexOf expects an object reference so you have to box the int, just like
you did for the writeline.

--

Kind regards,
Bruno van Dooren
(e-mail address removed)
Remove only "_nos_pam"
 

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