How do I check for a Null pointer in a composite reference ?

P

pamela fluente

I want a simple method or function to check if at least one of the
field in a composite object is null (nothing).

For instance, if Field5 is null I would like that a function such
as

AtLeastOneReferenceNull(Class1.Field3.Property4.Field5.something)

would return TRUE

where

Function AtLeastOneReferenceNull ( o as object) as boolean
' how ???
end function

or similar.

How can I do that (clearly without a slow try/catch) ?

-P
 
J

Jon Skeet [C# MVP]

I want a simple method or function to check if at least one of the
field in a composite object is null (nothing).

For instance, if Field5 is null I would like that a function such
as

AtLeastOneReferenceNull(Class1.Field3.Property4.Field5.something)

would return TRUE

You can't do that. By the time the method is called, the expression
will have been evaluated. You need:

if (Class1 == null ||
Class1.Field3 == null ||
Class1.Field3.Property4 == null ||
Class1.Field3.Property4.Field5 == null ||
Class1.Field3.Property4.Field5.something == null)
{
...
}

Do you often use expressions with that many levels of indirection
though? In the rare cases where I have several layers of indirection
like that, it's usually an error for any of the "early" levels to be
null anyway.

Jon
 
M

Marc Gravell

No easy way, without checking Class1 == null || Class1.Field3 == null
|| {etc}

Note that try/catch is not as slow as people often think... the
debugger might be fooling you here; but it isn't an elegant solution.

Another option (far from perfect, and only suitable for properties)
might be something using the component model... i.e.
SomeFunc(class1, "Field3.Property4.Field5")
with
bool SomeFunc(object component, string path) {
if(component==null) return true;
foreach(string section in path.Split('.')) {
component = TypeDescriptor.GetProperties(component)
[section].GetValue(component);
if(component == null) return true;
}
return false;
}

Direct reflection might work for fields, but I can't bring myself to
ever recommend coding against fields directly ;-p

Just a thought...

Marc
 
M

Marc Gravell

Just to clarify; "SomeFunc" as described would be noticeably slower
than either other option (try-catch / pyramid testing).
 
P

pamela fluente

Thanks you Jon , Thanks Marc,

I will be working on your insightful suggestions.

Actually I have often several levels of indirection in complex
programs and I would like
the possibility to check the whole thing is a simple easy way instead
of using all those ugly IF/andalso/orelse .

I was suspecting that perhaps using reflection something could be
done.
But actually reflections seems to work just on actual instances...

-P
 
P

pamela fluente

Just to clarify; "SomeFunc" as described would be noticeably slower
than either other option (try-catch / pyramid testing).

Are you sure about that? I would feel that the slowest is Try/catch.

In my experience Try/catch is the most terrible slodownthing to
use :)

I never use it unless there is an actual error to catch ...

I use often reflection (when restoring object with nonserialized
fields) and does not seem to be so bad.


-P
 
J

Jon Skeet [C# MVP]

Are you sure about that? I would feel that the slowest is Try/catch.

In my experience Try/catch is the most terrible slodownthing to
use :)

In the debugger, or in a "normal" environment?
I never use it unless there is an actual error to catch ...

I use often reflection (when restoring object with nonserialized
fields) and does not seem to be so bad.

Reflection is fairly slow. I wouldn't like to guess which would be
faster, although it will clearly depend on what proportion of the time
an exception is thrown. If you're particularly interested in the
performance of this part of the code, it would be worth benchmarking/
profiling.

Neither is particularly clean - reflection would require the
expression to be duplicated in some form (eg putting it in a string
literal) and catching an exception in this case just really isn't
nice. I would prefer to "design it away" in some form or other, so
that you have more control/understanding over when it's reasonable for
any particular part of the expression to be null.

Jon
 
M

Marc Gravell

Pretty much, yes; but it depends on how your code is structured. If
this isn't in a tight loop, then use which ever approach you like: you
will most likely never see an issue, so don't do premature
optimisation. But for certain the pyramid testing (see Jon's example)
is going to be the fastest.

Jon talks about quantified cost of exceptions here:
http://www.yoda.arachsys.com/csharp/exceptions.html
(with follow-up: http://www.yoda.arachsys.com/csharp/exceptions2.html)

This at least gives you some figures. As for reflection; following are
timings (ms) taken from 250k get/set pairs against a simple class
(actually it implements INotifyPropertyChanged for my purposes, but
there are no subscribers) with a checksum to ensure no compiler
optimisations; this shows the absolute cost of reflection (don't trust
the 0; obviously this is too tight a scale for just DateTime, but I'm
not going to bother changing it). For comparison, I have also included
some stats for my own "property-bag" implementation, which stores data
in a dictionary rather than fields and provides custom
PropertyDescriptor (via ICustomTypeDescriptor)... this improves
PropertyDescriptor (component-model) access, but at the cost of
levelling direct access... PropertyInfo (reflection) access is still
very slow though, but the aim here was to improve UI-binding access;
job done I believe ;-p

Simple class [250000]
Direct read 0
Direct write 40.0576
PropDesc read 5618.0784
PropDesc write 6669.5904
PropInfo read 4546.5376
PropInfo write 5688.1792

PropertyBag class [250000]
Direct read 260.3744
Direct write 400.576
PropDesc read 290.4176
PropDesc write 420.6048
PropInfo read 5457.848
PropInfo write 6899.9216

Marc
 
P

pamela fluente

Thank you.

Hmm interesting reading.
From my point of view should, however, be usually not so important
whether the try/catch takes a lot or little time, because personally I
would never use
to test anything. The times I use it is because there is a real
possible error you want to catch and then the execution
time is the last concern.

It is true that I found some very *rare* tasks for which I could not
find a substitute for try catch (for instance
determining if a port is being used by a program when opening a
socket), but hopefully it is used outside of tight loops.

These occurrences seems to me more a result of not having the
functionality directly within the language instead of a real
necessity.
Like for instance some people used a try/catch instead of isnumeric()
to determine if a field is a number....

-P
 
P

PS

pamela fluente said:
I want a simple method or function to check if at least one of the
field in a composite object is null (nothing).

For instance, if Field5 is null I would like that a function such
as

AtLeastOneReferenceNull(Class1.Field3.Property4.Field5.something)

would return TRUE

where

Function AtLeastOneReferenceNull ( o as object) as boolean
' how ???
end function

or similar.

How can I do that (clearly without a slow try/catch) ?

-P

You might consider some design changes. If you pass primitives to a method
then the method is much easier to test as it involves less setup. Also if
you find yourself having to make a lot of null testing then you can
encapsulate the behavior of what to do with a null reference into a Null
Object.

PS
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top