About Chilkat Callbacks in C# / .NET Core

When you set a callback in Chilkat (C#/.NET Core), the flow looks like this:

  1. Your managed C# code calls a Chilkat method.
  2. That Chilkat method runs inside native C++ code.
  3. Chilkat eventually triggers your C# callback delegate.

At this point, the call stack has crossed from managed → unmanaged → managed.

What happens if an exception occurs in your callback

If your C# callback throws an unhandled exception:

  • The exception won’t naturally propagate back through Chilkat’s native C++ layer.
  • Instead, the runtime will typically terminate the process, and it will appear as if the crash happened in Chilkat’s unmanaged code.
  • You’ll see strange or misleading symptoms, like access violations or execution engine errors, even though the root cause was in your callback.

Best practice

Yes — always wrap your callback code in a try/catch that swallows exceptions (or at least logs them cleanly without letting them escape). For example:

chilkatObj.SomeEventCallback = (sender, args) =>
{
    try
    {
        // Your logic here
    }
    catch (Exception ex)
    {
        // Handle it locally: log it, set a flag, etc.
        Console.Error.WriteLine($"Callback exception: {ex}");
        // Don’t rethrow — let Chilkat continue safely
    }
};

This ensures that exceptions never leak back through the C++ layer.

Why it matters

  • In ordinary managed-only code, unhandled exceptions bubble up and can be caught further up.
  • In mixed managed/unmanaged callback transitions, there isn’t a clean mechanism for that — so an exception looks like a crash in the native code.
  • By catching *everything* inside your callback, you preserve stability.

Clearing the Callback (resetting to null)

You can remove the callback by setting the delegate to null. However, the following line of code will produce a compiler warning.

sftp.setPercentDoneCb(null);

The warning produced is: warning CS8625: Cannot convert null literal to non-nullable reference type.

That warning comes from C#’s nullable reference type checking. The method sftp.setPercentDoneCb is declared to take a non-nullable delegate, so when you pass null directly, the compiler warns you.

You have a few ways to intentionally “clear” the callback:

1. Cast null to the correct delegate type

If the parameter type is (for example) Chilkat.PercentDoneCb, do this:

sftp.setPercentDoneCb((Chilkat.PercentDoneCb?)null);

This tells the compiler you really intend to pass a null delegate.

2. Use default

sftp.setPercentDoneCb(default!);

or

sftp.setPercentDoneCb(default(Chilkat.PercentDoneCb));

Both are equivalent to passing null but make your intent explicit.

3. Suppress the warning locally

If you want to keep it short and don’t care about nullable analysis:

sftp.setPercentDoneCb(null!);

(! is the null-forgiving operator.)


Recommended: Use option 1 or 2 — they are clear to both the compiler and human readers that you mean “no callback.”