Object reference not set to an instance of an object

Object reference not set to an instance of an object

Tripler123
Advocate Advocate
5,543 Views
5 Replies
Message 1 of 6

Object reference not set to an instance of an object

Tripler123
Advocate
Advocate

Almost three weeks ago I have a problem that I could not solve. I have searched and found many options but none has worked for me. The error when I try to count the elements that have the shared parameter "elemento" equal. I get the following error "Object reference not set to an instance of an object". My code is not very complex. I have tried to make conditional, but I do not find good results. I would be very grateful for any recommendations.

 

 

 

UIApplication uiApp = commandData.Application;
            UIDocument uiDoc = uiApp.ActiveUIDocument;
            Autodesk.Revit.ApplicationServices.Application app = uiApp.Application;
            Document doc = uiDoc.Document;

            lstElement = new List<Element>();
            lstElement = Util.AllElements(doc);

            List<string> lst = new List<string>();
            
            foreach (Element e in lstElement)
            {
                if (e.LookupParameter("Elemento") != null)
                {
                    lst.Add(Util.ParameterToString(e.LookupParameter("Elemento")));
                }
                
            }

var query = from item in lst
                        let palabra = item.ToString()
                        group item by palabra into g
                        select new { Key = g.Key, Values = g };

string nRepetidas = "";

                foreach (var item in query)
                {                              
                    nRepetidas += string.Format("{0} = {1}" + "\n", item.Key, item.Values.Count());                               
                }

TaskDialog Ventana = new TaskDialog("Cantidad de Elementos");

            Ventana.MainInstruction = "El proyecto tiene " + lstElement.Count.ToString();
            Ventana.MainContent = "Se han modelado los siguientes elementos :" + "\n" + "\n" +
                                  nRepetidas;
            Ventana.Show();


return Result.Succeeded;

The "Util" methods I use are the following

 

 

public static List<Element> AllElements (Document doc)

        {
            List<Element> lstElement = new List<Element>();

            FilteredElementCollector Columnas = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance))
                .OfCategory(BuiltInCategory.OST_StructuralColumns);
            List<Element> lstColumnas = Columnas.ToList();

            FilteredElementCollector Vigas = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance))
                .OfCategory(BuiltInCategory.OST_StructuralFraming);
            List<Element> lstVigas = Vigas.ToList();

            FilteredElementCollector Escaleras = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance))
                .OfCategory(BuiltInCategory.OST_Stairs);
            List<Element> lstEscaleras = Escaleras.ToList();

            List<Element> lstWall = FilterElementFamilyType(doc, typeof(Wall));

            List<Element> lstFloor = FilterElementFamilyType(doc, typeof(Floor));

            foreach (Element e in lstColumnas)
            {
                lstElement.Add(e);
            }

            foreach (Element e in lstVigas)
            {
                lstElement.Add(e);
            }


            foreach (Element e in lstFloor)
            {
                lstElement.Add(e);
            }

            foreach (Element e in lstWall)
            {
                lstElement.Add(e);
            }

            foreach (Element e in lstEscaleras)
            {
                lstElement.Add(e);
            }

            return lstElement;
        }
 public static string ParameterToString(Parameter param)
        {
            string val = "none";

            if (param == null)
            {
                return val;
            }

            switch (param.StorageType)
            {
                case StorageType.Double:
                    double dval = param.AsDouble();
                    val = dval.ToString();
                    break;

                case StorageType.Integer:
                    int iVal = param.AsInteger();
                    val = iVal.ToString();
                    break;

                case StorageType.String:
                    string sVal = param.AsString();
                    val = sVal;
                    break;

                case StorageType.ElementId:
                    ElementId idVal = param.AsElementId();
                    val = idVal.IntegerValue.ToString();
                    break;

                case StorageType.None:
                    break;

                default:
                    break;
            }
            return val;
        }

 

Regards,

0 Likes
5,544 Views
5 Replies
Replies (5)
Message 2 of 6

Tripler123
Advocate
Advocate

An exception of type 'System.NullReferenceException' occurred in LastPlannerSystem_4D.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object. occurred

0 Likes
Message 3 of 6

dantartaglia8696
Advocate
Advocate

Where is the error happening? I'm not seeing any error checking in your code (Try/Catch). I would start by troubleshooting the issue by trying to determine exactly where and when it happens then examine the element or other object's properties.

0 Likes
Message 4 of 6

RmsMali
Contributor
Contributor
  • This error could happen when your list is null/empty
  • From your code, it is evident that you try to filter and load the list of columns, list of framing, list of staircase, query. etc There are lot of possibilities this might happen at a later stage during the run. 
  • I suggest to implement two things:
    1.  "TRY CATCH" method. Enclose your code inside 'TRY.. CATCH' and find the exception. This could help resolve future issues.
    2.  Where ever you try to use, "For each XXX in YYYY", make sure to that the YYY LIST is not empty in the first place. Try to enclose that inside a IF STATEMENT or better add a function. The below example makes sure that, before your code is executed it is verified that the list is not null.
    3. Also, if you have some windowsform, make sure that your combobox, listbox are not having any null values. This might also return this error.

    4. list<element> yyyy = default(list<element>);
      if (yyyy.count != 0) {
      	foreach (element xxx in yyyy) {
      		// YOUR CODE GOES HERE
      	}
      } else {
      }
Message 5 of 6

RPTHOMAS108
Mentor
Mentor

I don’t think the FilteredElementCollector.ToList method is implemented to return something. In any case you should use ‘.ToElements’ or preferably ‘.ToElemenIDs’. I don’t know what the method ‘FilterElementFamilyType’ is doing internally (this is not an API method is it?), the null could be from that. However I recall a case where I used '.ToList' from mistaken habit and got null. The methods '.ToElements' and '.ToElementIDs' always returns an empty list or a list of items (rather than null or a list containing null items), there is then no null exception raised by iterating an empty list from one of these methods.

 

Rather than manually looping to add lists of items together you can use List(T).Union or even List(T).AddRange.

 

Structured exception handling has a performance cost which increases exponentially when used with a loop, you can watch it chugging along in the Immediate window with a noticeable delay with every catch. Better to test for conditions that will lead to exceptions than to handle the exceptions. I’m not sure if you get better performance by catching derived exceptions rather than the system.exception base class (which most catch).

0 Likes
Message 6 of 6

Tripler123
Advocate
Advocate

Thanks for the answers. Implement a try / catch and the error was as follows (Object
  Reference is set to an instance of a object.system.collections.listDictionaryInternal) This is a very rare error. Because it does so for certain elements. That is to say of an amount of 1000 elements, it performs without problem for 800 and then for an element it finds error.

0 Likes