1

I have this program that takes data from a database, puts it into a list, than reads data from a text file, compares two values - one from the text file and one from the database - according to a given index, and returns the higher value to another list. My problem is I can't handle the problem, when a line in the text file is missing an index. When calling function "zwr(index)", it gives a NullReferenceException, but I don't know how to handle it, typing catch nullreferenceexception at the bottom doesn't work and really I don't know where to go from now. I also have to make it so it doesn' crash when the user puts a wrong index. Here is my code, hope somebody can help:

    using System;
using FirebirdSql.Data.FirebirdClient;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace dokselect
{
    class indexstan
    {
        public string index;
        public double standysp;
    }

    class WynikPorownania
    {
        public string Indeks;
        public int Ilosc;
        public override string ToString()
        {
            return Indeks + " : " + Ilosc;
        }

    }
    class Program
    {
        public static void Main()
        {
            try
            {
                ///////CONNECTION

                string conn = "database=C:/PCBiznes/BAZA/IXION2_LOGMAG.FB;user=SYSDBA;password=masterkey;DataSource=192.168.24.112;Port=3050";
            FbConnection myConnection = new FbConnection(conn);
            FbDataReader myReader = null;

            string sql = "select KARTOTEKA.indeks,STANMAG.standysp FROM kartoteka INNER JOIN stanmag using(ID_KARTOTEKA) WHERE stanmag.ID_MAGAZYN=10002;";
            FbCommand myCommand = new FbCommand(sql, myConnection);

            myConnection.Open();
            myReader = myCommand.ExecuteReader();

            ///////LIST lista1
            List<indexstan> listadb = new List<indexstan>();
            double standysp;
            string index;
            while (myReader.Read())
            {
                index = myReader[0].ToString();
                standysp = Convert.ToDouble(myReader[1]);
                if(standysp<0)
                    {
                        standysp = 0;
                    }
                listadb.Add(new indexstan { index=index, standysp=standysp });
                //Console.WriteLine(myReader[0].ToString());
            }
            myConnection.Close();
            Console.WriteLine(listadb.Count);


            //RETURN STANDYSP FUNCTION
            double zwr(string myIndex)
            {
                var result = listadb.FirstOrDefault(listadb => listadb.index == myIndex).standysp;
                return result;
            }
            //zwr("EMPIS_DESKA_FASOLKA");

            //READ FROM TXT AND RETURN HIGHER
            string path = "C:/Users/Praktykant/Documents/textdocs/dok1.txt";
            
                List<WynikPorownania> listatf = File.ReadAllLines(path).Select(line =>
                {   
                    var linia = line.Split("=");
                    string index = linia[0];
                    int value = int.Parse(linia[1]);
                    if(value<0)
                    {
                        value = 0;
                    }
                    return new WynikPorownania { Indeks = index, Ilosc = (int)Math.Max(value, zwr(index)) };
                }).ToList();
                //DISPLAY ALL LISTATF CLASSES
                foreach (WynikPorownania WynikPorownania in listatf)
                {
                    Console.WriteLine(WynikPorownania);
                }
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine("Nie znaleziono pliku z podanej sciezki: "+ex);
            }
            catch (FormatException ex)
            {
                Console.WriteLine("Podaj indeksy i wartosci w formacie 'indeks=wartosc'. Blad zwrocil: "+ex);
            }
            catch (NullReferenceException ex)
            {
                Console.WriteLine("Nie podales prawidlowego indeksu. Blad zwrocil: "+ex);
                return;
            }
        }
    }
}

Handling the exception this way:

double zwr(string myIndex)
            {
                var result = listadb.FirstOrDefault(listadb => listadb.index == myIndex)?.standysp;
                return result ?? 0;
            }

Gets rid of the error, but still puts the data in the list resulting in something like this:

EMPIS_MAG_BUDOW : 12

: 8 <-Here is where the index wasn't given in the text file

SM_PORTAL_POL1 : 0

And I need it to stop compiling if the index is not given, cause this code will be later a part of a bigger program and this one block of code cannot collapse the whole thing. I tried using diffrent if statements in the function that returns data to the list and tried to throw in exceptions but nothing seemed to work...

shade999
  • 79
  • 7
  • 1
    User knows what a null exception is and how to handle it in general, but not how to apply the handling in his case. Therefore it should be reopened and guidance given on how to amend the code. – jason.kaisersmith Oct 22 '21 at 06:48

1 Answers1

2

Handle it this way:

           double zwr(string myIndex)
            {
                var result = listadb.FirstOrDefault(listadb => listadb.index == myIndex)?.standysp;
                return result ?? 0;
            }

You are getting the exception, because listadb.FirstOrDefault(listadb => listadb.index == myIndex) is null and you are trying to access .standysp; of null.

So use the ?. which will access the previous statement only when it is not null or return null itself.

The ?? returns the left side if not null and the right side if the left one is null.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61