views:

72

answers:

5
public class MyClass<T>
{
        public T this[int index]
        {
            get
            {
                ...
            }
            set
            {
                ...
            }
        }

        public void MyMethod<T>()
        {   
             int middleIndex = ...;              
             T value = this[middleIndex ];     
             ...             
        }           
}

The code won't compile because of the statement in MyMethod(). Is there another way of calling the indexer ?

Edit: Modified MyMethod()

Edit2: Compilation error

Error    6    Cannot implicitly convert type 'T [C:\MyClass.cs]' to 'T [C:\MyClass.cs]'

Thanks.

+2  A: 

Works fine for me:

public class MyClass<T>
{
    public T this[int index]
    {
        get
        {
            return default(T);
        }
        set
        {
        }
    }

    public void MyMethod(int index)
    {                 
         T value = this[index];     
    }           
}

Admittedly I had to introduce the index parameter into MyMethod, but I'm assuming you were wanting to get the index from somewhere... if that's not what you meant, please clarify.

Jon Skeet
A: 

you're not passing in a value for the index into the method MyMethod - can you post a little more code? It looks like something is missing...

mjd79
+1  A: 

Calling the indexer is fine, but it doesn't know which index you want. If you make index a parameter of MyMethod it will work fine.

If you're trying to get the current index or something then you need to store a private variable, wire it up in your indexer and access that.

Your edited code compiles fine...

public class MyClass<T>
{
        public T this[int index]
        {
            get
            {
                ...
            }
            set
            {
                ...
            }
        }

        public void MyMethod()
        {   
             int middleIndex = ...;              
             T value = this[middleIndex ];     
             ...             
        }           
}
kekekela
+1  A: 

This works fine for me:

public class MyClass<T>
{
    List<T> _items = new List<T>();

    public T this[int index]
    {
        get
        {
            return _items[index];
        }
    }

    public void MyMethod()
    {
        T value = this[2];
    }
}
David Moye
A: 

Your offending code is here:

public void MyMethod<T>()

Your class MyClass<T> already has a generic type parameter T, so the generic <T> on MyMethod is unnecessary

erash
It is offending because you're declaring a new T, and it has no relation to the outer T.
Simon Svensson