-3

I have a problem with the following code. I need to only create a new pcba node if it is different from the one created previously. I need to work with the same variable if that variable not change.

foreach (XmlNode node in dc.DocumentElement.ChildNodes)
            {
                PCBA pcb = null;

                if (serialPCB != node.Attributes["PCBpos"].Value.ToString())
                    pcb = new PCBA();

                pcb.PCBA_Status = status;
                long number = 0;
                bool validation = false;
                if (node.Attributes != null && node.Attributes["PCBpos"] != null)
                  {
                    validation = long.TryParse(node.Attributes["PCBpos"].Value, out number);
                  }
                 //bool validation = long.TryParse(node.Attributes["PCBpos"].Value, out number);
                if (validation == true)
                {
                    pcb.PCBA_POSITION = node.Attributes["PCBpos"].Value.ToString();
                    serialPCB = node.Attributes["PCBpos"].Value.ToString();

                    if (status != "PASS")
                    {
                        List<Group> groups = new List<Group>();
                        Group group = new Group();

                        group.Group_Name = node.Attributes["COMP_NAME"].Value.ToString();
                        group.Group_Status = status;
                        group.Group_FailureCode = node.Attributes["FaultName"].Value.ToString();

                        List<Measurement> measurements = new List<Measurement>();
                        Measurement measurement = new Measurement();
                        measurement.Measurement_Name = node.Attributes["COMP_NAME"].Value.ToString();
                        measurement.Measurement_Status = status;
                        DirectoryInfo di = new DirectoryInfo(dc.DocumentElement.Attributes["LOCATION"].Value.ToString());
                        var ruta = di.GetFiles(node.Attributes["COMP_NUMBER"].Value.ToString() + "-*");
                        if (ruta.Length > 0)
                            measurement.Measurement_ImagePath = di + "\\" + ruta[0].ToString();
                        measurements.Add(measurement);
                        group.Measurements = measurements;
                        groups.Add(group);
                        pcb.Groups = groups;
                    }

                    pcbas.Add(pcb);
                }
            }

1 Answers1

5

For every if there's an else.

In your case pcb is not assigned if the condition is false.

Set it first to null. then before using it again check if it's still null.

Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27