0

I get an exception on the List.Add line when trying to run this code:

        string searchText = searchByInterestBox.Text;
        List<string> checkedItems = null;

        if (m_BusinessLogic != null)    
        {
            if (searchText != string.Empty)  
            {
                try
                {
                    interestResultBox.Items.Clear();
                    foreach (var itemChecked in InterestsCheckedListBox.CheckedItems)
                    {
                        checkedItems.Add(itemChecked.ToString());
                    }

While debugging, when reaching the last line of code (checkedItems.Add) it says "Object Reference not set to an instance of an object"

Any idea what did I do wrong with the string list?

Thanks a lot. Itzik.

4 Answers 4

5

checkedItems is null, so you are getting an exception. You need to initialize it.

Instead of:

List<string> checkedItems = null;

Do:

IList<string> checkedItems = new List<string>();
Sign up to request clarification or add additional context in comments.

Comments

1

You shouldn't initialize the list with null:

List<string> checkedItems = new List<string>();

Comments

1

You have never created an instance of the list, try:

List<string> checkedItems = new List<string>();

Comments

1

The exception means your list has not been created yet (and is still null).

 List<string> checkedItems = new List<string>(); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.