0

I'm scratching my head a bit here.

I have a custom object which I'm trying to search for a property that starts with some text.

If I search for a property using == instead of StartsWith it doesn't error.

This works

Server serverObject = ServerObjectList.Find(n => n.Name == "Server001");

This gives a null ref exception

Server serverObject = ServerObjectList.Find(n => n.Name.StartsWith("Server001"));

Oddly, it works if the first object is the one your looking for.

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
RickBowden
  • 109
  • 1
  • 13

2 Answers2

0

your "ServerObjectList" list might be empty. At first it might be evaluating null == "" which gives false. in second statement, you are calling StartsWith function on a null, which gives you nullrefrenceexception. check if the list already has data.

Note: == operator is overloaded for strings. This might be doing null check before returning false.

Rakesh
  • 313
  • 4
  • 21
0

You should be doing like this as n may be null or Name may be null:

Server serverObject = ServerObjectList.Find(n => n!=null && n.Name!=null && n.Name.StartsWith("Server001"));
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
Deepak Bhatia
  • 1,045
  • 1
  • 8
  • 13