Hello everyone,
I've been coding small demos to improve my programming skills, and I've run into a problem getting indices of list items which I have been unable to figure out. I'm using C# 4.0, and Visual Studio Express 2010.
I've tried to use the IndexOf(T) method, but intellisense doesn't show it in its list. If I type it in manually, it shows as an error. I had thought that by default there would be a reference equality check and I wouldn't need to do anything explicit to use IndexOf. I've looked around to try and work out some solution, but everything that I can find just shows people using the function straightaway with no difficulty. This suggests to me that I'm missing something very basic and obvious, but whatever it is I am clearly missing it.
My code looks something like this (I can't post the actual code right now, as I'm not at my own computer). Where several Commodities have been instantiated above the function, List<Commodity> l is a list containing those Commodity objects, and c is the Commodity whose index I want:
// Class definition
class Commodity
{
string name;
public string Name { get; }
// Several int and double fields
}
// New .cs file below
// Commodities instantiated here, along with a List<Commodity> which is filled with them
public void SomeFunction(List<Commodity> l, Commodity c)
{
int index = l.IndexOf(c); // What I want to do, but can't seem to
Console.WriteLine("The index of {0} is {1}.", c.Name, index);
}
I have a few guesses about what might be the problem, but none of them have led to a resolution for me:
1. I'm relying too much on intellisense, and if I type the code as above it will compile
2. I need to inherit a particular interface in Commodity and/or overload functions and operators for Commodity for use with the IndexOf method. I've tried the overloading bit, but wouldn't be surprised to find out I did it incorrectly.
3. I need to code a delegate that can handle Commodity objects for use with IndexOf (and, more obviously, FindIndex(Predicate<T>), but I don't think I would need to use that function)
I know my fake code snippet above isn't worth much of anything, but is there anything that needs to be explicitly done to enable use of the IndexOf method of a list containing user defined objects? Or is the issue more likely some issue peculiar to my code that is preventing its use?