0
0
C Sharp (C#)programming~10 mins

EventHandler delegate pattern in C Sharp (C#) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare an event using the EventHandler delegate.

C Sharp (C#)
public class Button {
    public event [1] Click;
}
Drag options to blanks, or click blank then click option'
AFunc<int>
BAction
CEventHandler
DEventArgs
Attempts:
3 left
💡 Hint
Common Mistakes
Using Action or Func instead of EventHandler for events.
Using EventArgs as the delegate type.
2fill in blank
medium

Complete the code to raise the Click event safely.

C Sharp (C#)
protected virtual void OnClick() {
    [1]?.Invoke(this, EventArgs.Empty);
}
Drag options to blanks, or click blank then click option'
AClick
BClickEvent
COnClick
DRaiseClick
Attempts:
3 left
💡 Hint
Common Mistakes
Calling OnClick recursively instead of invoking the event.
Using a wrong event name.
3fill in blank
hard

Fix the error in the event subscription code.

C Sharp (C#)
Button btn = new Button();
btn.Click += [1];

void Btn_Click(object sender, EventArgs e) {
    Console.WriteLine("Button clicked");
}
Drag options to blanks, or click blank then click option'
ABtn_Click()
BBtn_Click(sender, e)
CBtn_Click(object, EventArgs)
DBtn_Click
Attempts:
3 left
💡 Hint
Common Mistakes
Adding parentheses when subscribing to the event.
Trying to pass parameters in the subscription.
4fill in blank
hard

Fill both blanks to declare and raise a custom event using EventHandler.

C Sharp (C#)
public class Alarm {
    public event [1] AlarmRaised;

    public void RaiseAlarm() {
        AlarmRaised[2].Invoke(this, EventArgs.Empty);
    }
}
Drag options to blanks, or click blank then click option'
AEventHandler
BEventHandler<TEventArgs>
CClick
D?
Attempts:
3 left
💡 Hint
Common Mistakes
Using EventHandler without a custom EventArgs class.
Omitting the null check operator when raising the event.
5fill in blank
hard

Fill all three blanks to create a dictionary of event handlers and invoke one safely.

C Sharp (C#)
var handlers = new Dictionary<string, [1]>();
handlers["start"] = (sender, e) => Console.WriteLine("Started");

if (handlers.TryGetValue("start", out var handler)) {
    handler[2].Invoke([3], EventArgs.Empty);
}
Drag options to blanks, or click blank then click option'
AEventHandler
B?
Cthis
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect delegate types in the dictionary.
Not using the null-conditional operator when invoking.