3

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

user409409
  • 31
  • 4

4 Answers4

4

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
  • 21,585
  • 10
  • 60
  • 75
2

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
  • 20,353
  • 1
  • 39
  • 56
1

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
  • 30,394
  • 6
  • 63
  • 80
0

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

Community
  • 1
  • 1
Adrian
  • 2,911
  • 1
  • 17
  • 24