IComparer Object reference not set to an instance of an object.

I'm not familiar with IComparer, but I'm getting a null reference
What am I doing wrong?
Private _comparer As IComparer

                    If _comparer.Compare(_lastValue, e.Item.DataItem) <> 0 Then
                        'add a header if it was different from the previous item.

                        Dim item As New GroupHeader()

                        item.DataItem = e.Item.DataItem

                    End If
Who is Participating?
Kevin CrossConnect With a Mentor Chief Technology OfficerCommented:
IComparer is an interface that should be implemented by a class to allow it be comparable.
Kevin CrossChief Technology OfficerCommented:
To be clear, the error you are getting is caused by the fact that you have not instantiated an object here:

Private _comparer As IComparer

To fix this normally in a declaration, you would add the New keyword and provide any constructor arguments necessary like so:

Private _comparer As New IComparer 'Invalid for IComparer

However, if you put this in code, you will see this will not work as IComparer is an Interface and cannot be instantiated; therefore, when you go to use it as an object, it is indeed a null reference since you cannot instantiate an object of that type in the first place.

Hopefully that makes sense.

Fernando SotoConnect With a Mentor RetiredCommented:
Hi JRockFL;

in your code snippet you have the following:

Private _comparer As IComparer

If _comparer.Compare(_lastValue, e.Item.DataItem) <> 0 Then

_comparer is a variable of type IComparer, which is an interface and can't be instantiated directly. Either you have a class that implements a customer Comparer or you cast an object that implemented a IComparer interface. The reason you are getting the error is that you do not have an instance of _comparer. What is the type of _lastValue and e.Item.DataItem?

JRockFLAuthor Commented:
Thank you for the replies

_lastValue is object
e.Item.DataItem is System.Data.DataRowView

Should this class implement the IComparer interface in order to compare those two objects?
Kevin CrossChief Technology OfficerCommented:
You can write a custom Comparer to compare objects that have special rules.  If you are just comparing the string values, then you can do this as string already implements Comparer.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.