Reputation: 33
I have a problem which I can't fix. It throws an exception only in C# code, in VB doesn't. The problem is just in events (oh, yes, it's classic - how it seemed to me by the number of very similar (or so) questions). BUT: I didn`t find an answer.
So, RaiseEvent works, calling the same event from C# - throws an exception. This event is declared in interface in the same compiled external dll. There's three similar events declared in common library, and there's all the same.
So, part of code in my common/shared interface library (I cut the most of code but the event declarations):
Public Interface ISolution
Event ErrorExecuting(ByVal sender As Object, ByVal iErrorCode As Integer)
Event ExecutionFinished(ByVal sender As Object, ByVal Cancelled As Boolean)
Event ExecutionStarted(ByVal sender As Object)
......
IExport is derived from ISolution And written Class-lib implements IExport (IExport implement ISolution events). That`s plugin system. I wrote earlier: there're a lot of interfaces implemet ISolution.
VB.NET code works fine
Declaration (implementation):
Public Event ExecutionStarted(ByVal sender As Object) Implements VmS.ISolution.ExecutionStarted
Calling:
RaiseEvent ExecutionStarted(Me)
C# throws 'Object referense not set to an instance of an object'
Declaration and implementation:
public event VmS.ISolution.ExecutionStartedEventHandler ExecutionStarted;
Calling:
ExecutionStarted(this);
There's no event-related code in any of projects, so I omitted remaining one.
I know that mistake is in invoking (from C#) that event.
I`m 10 years in VB5/6, 1 year in VB.NET, and 2 months in C#(( Please help) THANKS!
Upvotes: 0
Views: 347
Reputation: 1
You need create a function that call to this handler event, I explain me
if you have a code:
public event type_handler name_event(type_eventargs e);
you need create a function that call to name_event
private void on_name_event(type_eventargs e){
type_handler handler = name_event;
if(handler != null)
{
handler?.invoke(e);
}
}
for finalize use this
on_name_event(e);
you use this in any function for active this event
for example:
public class PersonEntity
{
event CreateHandler CreatePersonaEventHandler(CreateEventArgs e);
private onCreatePersonEventHandler(CreateEventArgs e){
CreateHandler handler = CreatePersonaEventHandler;
if(handler != null){
handler?.invoke(e);
}
}
public CreateUser(PersonEntity person){
CreateEventArgs dataEvent = new CreateEventArgs();
/*
your logic for create person
and
next to
*/
onCreatePersonEventHandler(dataEvent);//this line execute the event.
}
}
Upvotes: 0
Reputation: 17185
In C#, you need to check that the event is not null before raising it. If no one has registered to it, it is null.
You can either do
if (ExecutionStarted != null)
{
ExecutionStarted(this);
}
or, shorter
ExecutionStarted?.Invoke(this);
Upvotes: 2