-1

Edit: delete the link as comments say it could not access without an account. Codes are from MS official course at edx:

public class CustomList<T>
    {
        public T this[int index] { get; set; } //Error

        public void Add(T item)
        {
            // Method logic goes here.
        }
        public void Remove(T item)
        {
            // Method logic goes here.
        }
    }

Expected: no errors

Actual: Error: get must declare a body because it's not marked as abstract, extern, or partial.(CS0501)

Y Zhu
  • 43
  • 6
  • 1
    The link you provided isn't accessible unless you have a courses.edu account, btw – Spinnaker Jan 31 '19 at 22:28
  • 3
    The content you reference in your link is inaccessible due to a login restriction. What is your actual question? The example code clearly isn't valid - the error you are getting is what you should get. – Martin Jan 31 '19 at 22:28
  • 2
    This code is trying to combine two different things that don't mix. The syntax `this[int index]` is for declaring an [indexer](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/); `{ get; set; }` is for an [auto-implemented property](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties). You can't use them both. See the MSDN links for examples of how to fix. – BJ Myers Jan 31 '19 at 22:31
  • Possible duplicate of [Easy creation of properties that support indexing in C#](https://stackoverflow.com/questions/3344620/easy-creation-of-properties-that-support-indexing-in-c-sharp) – Gauravsa Jan 31 '19 at 22:50
  • @Gauravsa - It's not exactly a duplicate of that question, though. The problem isn't that OP needs to easily implement an indexer. The problem is that a so-called educational site is presumably presenting this code as valid...but it's not. – madreflection Jan 31 '19 at 22:54

2 Answers2

3

The indexer has to have a backing field, it's a bit like an operator overload, rather than a property.

So you need to have some field for the operator to work on, here I have just used an empty array.

    private T[] range = new T[0];

    public T this[int index]  
    {  
        get  
        {  
            return range[index];  
        }  
        set  
        {  
            range[index] = value;  
        }  
    }  
tigerswithguitars
  • 2,497
  • 1
  • 31
  • 53
1

What you need to do is define the get and set for the "this" property.

Example:

public class CustomList<T>
{
    private List<T> internalList = new List<T>();
    public T this[int index] { 
        get{ return internalList[index]; } 
        set{ internalList[index] = value;} 
    } //Error

    public void Add(T item)
    {
        // Method logic goes here.
    }
    public void Remove(T item)
    {
        // Method logic goes here.
    }
}
ZarX
  • 1,096
  • 9
  • 17