views:

1177

answers:

2

I am testing a function pointer called ErrorLoggingMethod in a C# DLL to prevent exceptions due to a null value, as below, but it seems that at runtime, the function is actually being executed when I really mean to test its delegate for null. I am inadvertently getting a null exception as a result--just what I am trying to avoid! My original intention was to help programmers in case they forgot to set that delegate. I want to provide a dummy function in such a case. If this won't work, how can I check whether the delegate is null?

udt.DatabaseConnectionString = InteractiveDatabaseConnection.AddSQLConnection(udt.ErrorLoggingMethod != null ? udt.ErrorLoggingMethod : CMAC_DummyErrorLoggingMethod);
+3  A: 

Are you sure you don't get the exception as a result of udt being null? You're not calling any function in the above code, you pass a delegate to the method AddSQLConnection.

Konrad Rudolph
A: 

I might not be understanding what you're asking but...If you're trying to know whether the delegate has any methods in its invocation list you can just check the length of the list...

if (ErrorLoggingMethod.GetInvocationList().Length(0) == 0){
    //Add your default handler to the delegate
}

Then run your AddSQLConnection method...

Jason Punyon
JPunyon, since my delegate could have many subscribers, it would seem your answer is most appropriate. Also I just noticed that in my original code, I omitted the parameters in the true and the false sides of the : operator when I truly intended to call the methods. I'm surprised it even compiled!
JoseRosario
My mistake: I thought I made a booboo by not providing an argument list to the function delegates passed to my AddSQLConnection function and thought the C# compiler wrongly accepted it...actually, AddSQLConnection expects a function delegate itself so I had coded it right; the C# compiler is fine ;)
JoseRosario