1

I'm having a problem with the delegate not delegating... I have an object called Tweet that has a string text and an int score. I want to sort the array of tweet objects(twtArray) in order of the score. This is the code I have:

Array.Sort(twtArray, delegate(Tweet twt1, Tweet twt2)
        {
            return twt1.score.CompareTo(twt2.score); //(twt1.score - twt2.score)
        });

and it throws:

System.NullReferenceException: Object reference not set to an instance of an object. at System.Array.FunctorComparer`1.Compare(T x, T y)

Whilst debugging, I noticed that the first comparison works but in the second comparison, twt2 is null. And it can't be null because I definitely have 8 elements in the array. I've tried reversing twt1 and twt2 as well but makes no difference. I also tried making my own comparison method in the Tweet class but again, same thing. Any help would be appreciated!

Also, I dont think this is a duplicate of this question: List.Sort in C#: comparer being called with null object because i tried all the possible solutions from this but it's not working. i've also searched a lot on google :(

Community
  • 1
  • 1
koko
  • 315
  • 2
  • 6
  • Even if you have an `Tweet[]` with 8 elements they can be null: `Tweet[] twtArray = new Tweet[8];` – Tim Schmelter Jul 23 '14 at 12:03
  • I meant that the Tweet[] is of size 20 and I can see that there are 8 Tweet objects in there (with correct text and score values) in the first line of my code. – koko Jul 23 '14 at 12:04
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Dirk Jul 23 '14 at 12:07

2 Answers2

3

Even if you have a Tweet[] with 8 elements some can be null:

Tweet[] twtArray = new Tweet[8]; // all instances are null

You: The Tweet[] is of size 20 and I can see that there are 8 Tweet objects in there (with correct text and score values) in the first line of my code.

So the array's size is 20 but only 8 are initialized? (see above) Array.Sort needs to compare all with all others.

You could prevent it in this way:

Array.Sort(twtArray, delegate(Tweet twt1, Tweet twt2)
{
    if(twt1 == null && twt2 == null) return 0;
    if(twt1 == null) return -1;
    if(twt2 == null) return  1;
    return twt1.score.CompareTo(twt2.score); 
});
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

When you're working with an array that's only partially filled, that indicates that you don't actually want an array, you want List<T>.

Using that, you can have a collection that contains 8 items, but can be later expanded to 20 efficiently. And when you call Sort() on such list, you're not going to have any problems with nulls.

svick
  • 236,525
  • 50
  • 385
  • 514