JoseRosario
JoseRosario

Reputation: 3

Testing a C# Function Pointer (Delegate) for Null

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);

Upvotes: 0

Views: 1973

Answers (2)

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...

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

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.

Upvotes: 3

Related Questions