Aserre
Aserre

Reputation: 5072

IEnumerable.MoveNext() returns True but IEnumerable.Current raises a System.NullReferenceException

I am building a C# application using the Manatee.Trello package to handle Trello's API.

I am currently trying to get the first result returned by the Search function. The Search.Boards element implements the IEnumerable<Board> interface.

This is what I currently have:

Search mySearch = new Search(SearchFor.IsOpen(), 100, SearchModelType.Boards);
foreach (Board b in mySearch.Boards) {
      Console.WriteLine("Board Name:{0} _ ID:{1}", b.Name, b.Id);
}
mySearch.Boards.GetEnumerator().Reset();
bool next=mySearch.Boards.GetEnumerator().MoveNext();
Console.WriteLine("MoveNext:{0}", next);
Console.WriteLine("\nBoard Name:{0}", mySearch.Boards.GetEnumerator().Current.ToString());

The first foreach loop works fine and displays all the boards my user has access to. Console.WriteLine("MoveNext:{0}", next) works as well and displays MoveNext:True. However, the last line returns a System.NullReferenceException: Object reference not set to an instance of an object

What is wrong with my code? I know mysearch contains data (I tried copying the foreach loop just after the MoveNext() call, and it works fine). Is there a simpler method to access a specific element of my search result ?

Upvotes: 2

Views: 2767

Answers (1)

nvoigt
nvoigt

Reputation: 77334

GetEnumerator() returns a new enumerator each call. Whatever you think you are doing with the calls to it, you aren't doing it. The result is lost after each line because you don't keep the enumerator variable.

Generally speaking, C# is a high level language. Try to not go down to the depths of manual loop handling. Your foreach is just fine.

To access members of an enumeration outside of a foreach loop, LinQ is the easiest way:

var board = mySearch.Boards.FirstOrDefault(board => board.Name == "WhatImLookingFor");

Upvotes: 4

Related Questions