Home > Net >  Cannot apply indexing with [] to an expression of type 'type'
Cannot apply indexing with [] to an expression of type 'type'

Time:12-15

everyone! I'm new in programming so I hope for your help! I'm trying to return and index of the array but have no idea what does the error mean. I got this one for the first time.

this is my first class

using System;
using System.Linq;

public class Group
{
private Student[] students;

public Group(Student[] students)
{
    if(students.Length < 5)
    {
        throw new ArgumentException("Incorrect group");
    }

    this.students = students;
}

public int IndexOfMaxGrade()
{
    Student[] sorted = students.OrderBy(c => c.grade).ToArray();
    //int max = sorted[^1].grade;

    //foreach (var item in students)
    //{
    //    if(item.grade == max)
    //    {
            
    //    }
    //}

    return Array.IndexOf(students, sorted[^1].grade);
}

public int IndexOfMinGrade()
{
    Student[] sorted = students.OrderBy(c => c.grade).ToArray();

    return Array.IndexOf(students, sorted[0].grade);
}
}

and I got on "Cannot apply indexing with [] to an expression of type 'type'" on this code (last 2 lines)

    Group studentGroup;

    try
    {
        studentGroup = new Group(students.ToArray());
    }
    catch (ArgumentException argumentException)
    {
        Console.WriteLine(argumentException.Message);
        return;
    }

    Console.WriteLine(studentGroup[studentGroup.IndexOfMinGrade()]);
    Console.WriteLine(studentGroup[studentGroup.IndexOfMaxGrade()]);
}
}

CodePudding user response:

If you want to index a Group directly, you'll have to provide an indexer:

public class Group
{
  public Student this[int i]{
    get { return students[i]; }
    set { students[i] = value; }
  }
  ...

You see, your Group has an array of students, but that doesn't mean it is, itself, directly indexable like an array is..

When you did:

Group studentGroup = ...

You later tried to access something at some index within the Group:

studentGroup[studentGroup.IndexOfMinGrade()];     //like this
studentGroup[1];                                  //or like this, for example

C# won't look at your Group type and think "it has only one data item inside, which is an array, so I will allow someone to put an index specifier like [1] next to an instance of a Group, and I'll retrieve the item from within the internal array"..

..it just says "cannot index a Group"


If you add an indexer, then happy days. You could also have done something like:

class Group{
  ...

  public Student GetStudentAt(int index){
    return students[index];
  }

And then called:

  Console.WriteLine(studentGroup.GetStudentAt(studentGroup.IndexOfMinGrade()));

Conceptually equivalent..

  • Related