Strange indexer behaviour

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello
I have two classes:

public class ScheduleItem
{
private string s_name;

public ScheduleItem(){ s_name="default";}
public string Name{
get{return s_name;}
set{s_name=value;}
}
}

and the second class:

public class Schedules
{
ScheduleItem[] sched;
private int i_lenght;

public Schedules (int howManyItems)
{
sched= new ScheduleItem[howManyItems];
i_lenght = howManyItems;
}
public int Lenght{ get... set...}

public ScheduleItem this[int idx]
{
get... set.. (here I wrote indexer, it works)
}

}


When I put an instance in my application:
Schedule SCH = new Schedule(2);
SCH[0].Name = "Bill Gates";

i got exception.... why? it should work in my opinion....
 
When I put an instance in my application:
Schedule SCH = new Schedule(2);
SCH[0].Name = "Bill Gates";

i got exception.... why? it should work in my opinion....

This has nothing to do with indexers - it's just normal arrays. When
you create an array, it doesn't populate it with objects. In other
words, your SCH[0] is returning null, which you're then dereferencing,
hence the exception.

You need to actually create an instance of ScheduleItem at some
stage...
 
Ok, but I thought I had created new instances of ScheduleItem in Schedules'
constructor:
public Schedules (int howManyItems)
{
sched= new ScheduleItem[howManyItems];
i_lenght = howManyItems;
}
What else I misunderstood? SO what it the right way to do this?
Thanks

Jon Skeet said:
When I put an instance in my application:
Schedule SCH = new Schedule(2);
SCH[0].Name = "Bill Gates";

i got exception.... why? it should work in my opinion....

This has nothing to do with indexers - it's just normal arrays. When
you create an array, it doesn't populate it with objects. In other
words, your SCH[0] is returning null, which you're then dereferencing,
hence the exception.

You need to actually create an instance of ScheduleItem at some
stage...
 
Ok, I must be blind....

Schedules schedules = new Schedules();
....
for(int i=0;i<schedules .Lenght;i++) schedules = new ScheduleItem();


It works
Thanks, Jon

DAMAR said:
Ok, but I thought I had created new instances of ScheduleItem in Schedules'
constructor:
public Schedules (int howManyItems)
{
sched= new ScheduleItem[howManyItems];
i_lenght = howManyItems;
}
What else I misunderstood? SO what it the right way to do this?
Thanks

Jon Skeet said:
When I put an instance in my application:
Schedule SCH = new Schedule(2);
SCH[0].Name = "Bill Gates";

i got exception.... why? it should work in my opinion....

This has nothing to do with indexers - it's just normal arrays. When
you create an array, it doesn't populate it with objects. In other
words, your SCH[0] is returning null, which you're then dereferencing,
hence the exception.

You need to actually create an instance of ScheduleItem at some
stage...
 
Back
Top