0

This is the code to find the product names using keyword. I am getting "Null referrence exception" please resolve this problem. I am getting exception in if statement.

 static void Main(string[] args)
        {
            try
            {
                int n;
                string[] item = null;
                string[] productName = new string[6];
                string word;
                int i;
                bool flag = false;
                Console.WriteLine("enter the no of products");
                n = Convert.ToInt32(Console.ReadLine());
                for (i = 0; i < n; i++)
                {
                    productName[i] = Console.ReadLine();
                }
                Console.WriteLine("enter the keyword to search");
                word = Console.ReadLine();
                foreach (string item1 in productName)
                {
                    if (item1.Contains(word)) //NullReferenceException
                    {
                        flag = true;
                        item = item1.Split(' ');
                        Console.WriteLine("item:" + item[0]);
                    }
                }

                if (!flag)
                {
                    Console.WriteLine("not found");
                    Console.ReadLine();
                }

            }
            catch (NullReferenceException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }

is there any other way to code this..?

user3142089
  • 11
  • 1
  • 2
  • you are declaring 6 array members here: string[] productName = new string[6]; So when user will enter 6, the program should work fine, and show the error if it is less than or greater than 6 – Usman Waheed Dec 30 '13 at 11:40
  • productName[i] has value if you put n = 1 then your array will have value ONLY on the first item and the other till be null. – kostas ch. Dec 30 '13 at 11:45
  • What do you want to do with this code? – kostas ch. Dec 30 '13 at 11:48

3 Answers3

2

One of your products is null. You're allocating space for 6.. but if you don't enter 6.. iterating over them will cause a NullReferenceException.

The easy fix is to filter them out:

foreach (string item1 in productName.Where(x => !string.isNullOrEmpty(x))
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
1
if (item1 != null && item1.Contains(word)) 
0

The problem here is you are initializing the array as this.

string[] productName = new string[6];

But, if your input n is less than 6, the last few items will be null. Also, this will cause index issues if n is greater than 6.

I would suggest, moving this statement below

n = Convert.ToInt32(Console.ReadLine());

and, change 6 to n.

string[] productName = new string[n];
Buddhima Gamlath
  • 2,318
  • 1
  • 16
  • 26