XbimEssentials icon indicating copy to clipboard operation
XbimEssentials copied to clipboard

NullReferenceException in CountOf

Open ChernyshevDS opened this issue 1 year ago • 2 comments

Hello, xBim team! I guess there's an error in the implementation of PersistedEntityInstanceCache.CountOf<T>. I'm trying to count number of instances of IIfcRelDefinesByProperties with this code:

var model = IfcStore.Open(filePath);
var count = model.Instances.CountOf<IIfcRelDefinesByProperties>();

This code crashes with NullReferenceException. By the way, this code works fine:

var count = store.Instances.OfType<IIfcRelDefinesByProperties>().LongCount();

I hoped that CountOf may be more efficient than OfType<>.LongCount, but I may be misusing this method.

I'm using Xbim.Essentials 5.1.323 Nuget package. Thanks in advance.

ChernyshevDS avatar Jul 20 '22 11:07 ChernyshevDS

The performance should be just about the same. OfType<T>() will only return handles to entities and will not try to activate and parse their data until you try to access any properties. So, it should be fast and lightweight. But CountOf<T>() should obviously work as well. Can you try to investigate in the source?

martin1cerny avatar Jul 20 '22 11:07 martin1cerny

Well, looking at source code of CountOf method there's a line:

private long CountOf(Type theType)
{
    var entityLabels = new HashSet<int>();
    var expressType = Model.Metadata.ExpressType(theType);    // <=

    ... dereferencing expressType

but source code for OfType method has comment that

// when searching for Interface types expressType is null

so by analogy with OfType I guess it should be fixed with following patch (can not test now, sorry):

patch.txt

ChernyshevDS avatar Jul 22 '22 10:07 ChernyshevDS