Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare an event named OnChange.
C Sharp (C#)
public event EventHandler [1]; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different event name than declared.
Forgetting to declare the event type.
✗ Incorrect
The event name is
OnChange, so the blank should be filled with OnChange.2fill in blank
mediumComplete the code to safely raise the event OnChange using a local copy.
C Sharp (C#)
var handler = [1]; if (handler != null) { handler(this, EventArgs.Empty); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the event name.
Not checking for null before invoking the event.
✗ Incorrect
To safely raise the event, we copy
OnChange to a local variable handler and check if it is not null.3fill in blank
hardFix the error in the event invocation by completing the code.
C Sharp (C#)
OnChange[1](this, EventArgs.Empty); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call the event like a method without
.Invoke.Using non-existent methods like
.Raise or .Call.✗ Incorrect
In C#, to invoke an event delegate safely, use the
.Invoke method.4fill in blank
hardFill both blanks to create a method RaiseOnChange that safely raises the event.
C Sharp (C#)
protected virtual void RaiseOnChange()
{
var handler = [1];
if (handler [2] null)
handler(this, EventArgs.Empty);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
== instead of != in the if condition.Copying the wrong event name.
✗ Incorrect
We copy the event
OnChange to handler and check if it is not equal (!=) to null before invoking.5fill in blank
hardFill all three blanks to raise the event with a custom EventArgs subclass MyEventArgs.
C Sharp (C#)
protected virtual void RaiseOnChange(MyEventArgs e)
{
var handler = [1];
if (handler != null)
handler([2], [3]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing
EventArgs.Empty instead of the custom e.Not checking if the event is null before invoking.
✗ Incorrect
We copy the event
OnChange to handler, check for null, then invoke it passing this and the custom event args e.