views:

58

answers:

4

Hi!

This may be a newbie question...

In my code I can easily use "where Obj.Feld = String", but using "where Obj.Feld.StartsWith("a")" doesn't work. See the following two functions:

    Public Function EntriesByFileName(ByRef Database() As Entry, ByVal Filename As _
  String) As IEnumerable(Of Entry)
        Dim Result As IEnumerable(Of Entry) = From EntryObject In Database _
        Where (EntryObject.FileName = Filename) Select EntryObject
        Return Result
    End Function

    Public Function EntriesLikeFileName(ByRef Database() As Entry, ByVal _
      Filename As String) As IEnumerable(Of Entry)
        Filename = Filename.ToLower
        Dim Result As IEnumerable(Of Entry) = From EntryObject In Database _
          Where EntryObject.FileName.StartsWith("a") Select EntryObject
        Return Result
    End Function

The first function (byFileName) works fine. The second function (LikeFileName) doesn't. Using Startswith I get "Object reference not set to an instance of an object." What am I doing wrong?

Database is an array of Objects, a structure consisting of strings

+2  A: 

Make sure Database does not contain any null entries. You can apply the = operator on null, but you cannot call any methods on it, so StartsWith() fails.

tdammers
+4  A: 

EntryObject.FileName can be NULL, so EntryObject.FileName.StartsWith(..) can throw a NullReferenceException.

Change the condition to first check for NULL eg

if EntryObject.FileName <> nothing AndAlso EntryObject.FileName.StartsWith(..) 

Using AndAlso here employs short-circuiting, which means that if the first condition is not met, the second won't be evaluated and hence we can't get the NullReferenceException.

Winston Smith
I thought you needed `AndAlso` to get short-circuiting.
Gabe
@Gabe Thanks, you're correct of course. I'm no expert on VB. Answer updated.
Winston Smith
THANK YOU SO MUCH! You were so right!
A: 

If you are using linq to entities then I don't think it supports startswith or contains. See this post Stackoverflow post

antonlavey
This has nothing to do with the problem at hand.
Winston Smith
+1  A: 

Hi,

looks like one of the EntryObject object has FileName property set to null. In first method it won't be detected because you can compare a null value to other value, but in second method, you are trying to invoke a method on a null object which will throw exception.

decyclone