Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Custom event arguments in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Custom Event Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this custom event argument example?

Consider the following C# code that defines a custom event argument and raises an event. What will be printed when the event is triggered?

C Sharp (C#)
using System;

public class MessageEventArgs : EventArgs
{
    public string Message { get; }
    public MessageEventArgs(string message) => Message = message;
}

public class Publisher
{
    public event EventHandler<MessageEventArgs>? MessageSent;

    public void SendMessage(string msg)
    {
        MessageSent?.Invoke(this, new MessageEventArgs(msg));
    }
}

public class Subscriber
{
    public void OnMessageReceived(object? sender, MessageEventArgs e)
    {
        Console.WriteLine($"Received: {e.Message}");
    }
}

class Program
{
    static void Main()
    {
        var pub = new Publisher();
        var sub = new Subscriber();
        pub.MessageSent += sub.OnMessageReceived;
        pub.SendMessage("Hello World");
    }
}
ANo output
BReceived: MessageEventArgs
CHello World
DReceived: Hello World
Attempts:
2 left
💡 Hint

Look at how the event handler prints the Message property from the custom event args.

🧠 Conceptual
intermediate
1:30remaining
Which statement about custom event arguments is true?

Choose the correct statement about creating and using custom event argument classes in C#.

ACustom event argument classes can only contain public fields, not properties.
BCustom event argument classes must inherit from <code>EventArgs</code> to be used in events.
CEvents cannot use custom event argument classes; only <code>EventArgs</code> can be used.
DCustom event argument classes must be sealed and cannot be inherited.
Attempts:
2 left
💡 Hint

Think about the base class convention for event argument classes in .NET.

🔧 Debug
advanced
2:00remaining
What error does this code produce?

Examine the following code snippet. What error will occur when compiling or running it?

C Sharp (C#)
using System;

public class DataEventArgs : EventArgs
{
    public int Data { get; set; }
}

public class Emitter
{
    public event EventHandler<DataEventArgs> DataChanged;

    public void ChangeData(int value)
    {
        DataChanged(this, new DataEventArgs { Data = value });
    }
}

class Program
{
    static void Main()
    {
        var emitter = new Emitter();
        emitter.ChangeData(10);
    }
}
ACompilation error: event invocation syntax incorrect
BNo error, prints nothing
CNullReferenceException at runtime
DInvalidCastException at runtime
Attempts:
2 left
💡 Hint

Check if the event has any subscribers before invoking it.

📝 Syntax
advanced
2:00remaining
Which option correctly declares and raises a custom event with arguments?

Choose the correct code snippet that declares a custom event with custom event arguments and raises it safely.

A
public event EventHandler&lt;MyArgs&gt; MyEvent;

protected virtual void OnMyEvent(string msg) {
    MyEvent?.Invoke(this, new MyArgs(msg));
}
B
public event EventHandler&lt;MyArgs&gt; MyEvent;

protected virtual void OnMyEvent(string msg) {
    if (MyEvent != null) MyEvent(this, msg);
}
C
public event EventHandler&lt;MyArgs&gt; MyEvent;

protected virtual void OnMyEvent(string msg) {
    MyEvent(this, new MyArgs(msg));
}
D
public event EventHandler&lt;MyArgs&gt; MyEvent;

protected virtual void OnMyEvent(string msg) {
    MyEvent.Invoke(new MyArgs(msg));
}
Attempts:
2 left
💡 Hint

Look for safe invocation and correct argument types.

🚀 Application
expert
2:30remaining
How many items are in the event args list after this code runs?

Given the code below, how many items will be in the Numbers list inside NumbersEventArgs when the event is raised?

C Sharp (C#)
using System;
using System.Collections.Generic;

public class NumbersEventArgs : EventArgs
{
    public List<int> Numbers { get; }
    public NumbersEventArgs(List<int> numbers) => Numbers = numbers;
}

public class NumberGenerator
{
    public event EventHandler<NumbersEventArgs>? NumbersGenerated;

    public void Generate()
    {
        var nums = new List<int>();
        for (int i = 0; i < 5; i++)
        {
            nums.Add(i);
            if (i == 2)
                NumbersGenerated?.Invoke(this, new NumbersEventArgs(new List<int>(nums)));
        }
    }
}

class Program
{
    static void Main()
    {
        var gen = new NumberGenerator();
        gen.NumbersGenerated += (s, e) => Console.WriteLine(e.Numbers.Count);
        gen.Generate();
    }
}
A3
B5
C2
D0
Attempts:
2 left
💡 Hint

Look at when the event is raised and how many numbers have been added at that moment.

Practice

(1/5)
1. What is the main purpose of creating a custom class that inherits from EventArgs in C#?
easy
A. To replace the EventHandler delegate entirely.
B. To prevent events from being raised multiple times.
C. To send additional data with an event when it is raised.
D. To automatically handle exceptions in event handlers.

Solution

  1. Step 1: Understand the role of EventArgs

    The EventArgs class is used to pass data with events. Creating a custom class inheriting from it allows adding extra information.
  2. Step 2: Identify the purpose of custom event arguments

    Custom event argument classes let you send specific data related to the event, making event communication clearer.
  3. Final Answer:

    To send additional data with an event when it is raised. -> Option C
  4. Quick Check:

    Custom EventArgs = Extra event data [OK]
Hint: Custom EventArgs carry extra info with events [OK]
Common Mistakes:
  • Thinking custom EventArgs replace EventHandler delegate
  • Believing custom EventArgs stop event repetition
  • Assuming custom EventArgs handle exceptions automatically
2. Which of the following is the correct way to declare a custom event argument class named MyEventArgs with a string property Message?
easy
A. public class MyEventArgs : EventArgs { public int Message { get; set; } }
B. public class MyEventArgs { public string Message { get; set; } }
C. public class MyEventArgs : EventHandler { public string Message; }
D. public class MyEventArgs : EventArgs { public string Message { get; set; } }

Solution

  1. Step 1: Check inheritance from EventArgs

    The custom event argument class must inherit from EventArgs to be used properly in events.
  2. Step 2: Verify property type and syntax

    The property Message should be a string with get and set accessors for data storage.
  3. Final Answer:

    public class MyEventArgs : EventArgs { public string Message { get; set; } } -> Option D
  4. Quick Check:

    Custom EventArgs inherit EventArgs + correct property type [OK]
Hint: Custom EventArgs must inherit EventArgs and use correct property types [OK]
Common Mistakes:
  • Forgetting to inherit from EventArgs
  • Using EventHandler as base class instead of EventArgs
  • Declaring property with wrong type
3. Consider the following code snippet:
public class MyEventArgs : EventArgs { public int Number { get; set; } }

public class Publisher {
    public event EventHandler<MyEventArgs> OnNumberChanged;
    public void ChangeNumber(int num) {
        OnNumberChanged?.Invoke(this, new MyEventArgs { Number = num });
    }
}

public class Subscriber {
    public void Subscribe(Publisher pub) {
        pub.OnNumberChanged += HandleNumberChanged;
    }
    private void HandleNumberChanged(object sender, MyEventArgs e) {
        Console.WriteLine($"Number is {e.Number}");
    }
}

// Main method
var pub = new Publisher();
var sub = new Subscriber();
sub.Subscribe(pub);
pub.ChangeNumber(42);

What will be the output when this code runs?
medium
A. Number is 42
B. Number is 0
C. No output, event not raised
D. Compilation error due to event handler signature

Solution

  1. Step 1: Understand event raising and subscription

    The Publisher raises OnNumberChanged event with MyEventArgs containing the number passed.
  2. Step 2: Check subscriber's event handler output

    The subscriber prints the Number property from the event args, which is set to 42.
  3. Final Answer:

    Number is 42 -> Option A
  4. Quick Check:

    Event raised with Number=42 prints "Number is 42" [OK]
Hint: Event args data prints exactly as passed in event [OK]
Common Mistakes:
  • Assuming event is not raised or subscribed
  • Confusing default values with passed values
  • Mistaking event handler signature causing errors
4. The following code attempts to raise a custom event with arguments but causes a runtime error. What is the most likely cause?
public class MyEventArgs : EventArgs { public string Info { get; set; } }

public class Publisher {
    public event EventHandler<MyEventArgs> OnInfoChanged;
    public void RaiseEvent() {
        OnInfoChanged(this, new MyEventArgs { Info = "Hello" });
    }
}

// Usage
var pub = new Publisher();
pub.RaiseEvent();
medium
A. OnInfoChanged event is null because no subscribers are attached.
B. MyEventArgs does not inherit from EventArgs.
C. Event handler signature does not match the event declaration.
D. The Info property is not initialized before raising the event.

Solution

  1. Step 1: Check event invocation safety

    The event OnInfoChanged is invoked without checking if it has subscribers, so if null, it causes a runtime NullReferenceException.
  2. Step 2: Identify missing subscriber check

    Before invoking, the code should check if OnInfoChanged is not null to avoid errors.
  3. Final Answer:

    OnInfoChanged event is null because no subscribers are attached. -> Option A
  4. Quick Check:

    Invoke event without subscribers = NullReferenceException [OK]
Hint: Always check event is not null before invoking [OK]
Common Mistakes:
  • Forgetting to check event for null before invoking
  • Assuming event has subscribers by default
  • Confusing property initialization with event subscription
5. You want to create a custom event argument class ProgressEventArgs that includes a percentage (int) and a message (string). You also want to raise an event ProgressChanged in a class Downloader that sends this data. Which of the following code snippets correctly implements this scenario?
hard
A. public class ProgressEventArgs { public int Percentage { get; set; } public string Message { get; set; } } public class Downloader { public event EventHandler ProgressChanged; public void ReportProgress(int percent, string msg) { ProgressChanged?.Invoke(this, new ProgressEventArgs { Percentage = percent, Message = msg }); } }
B. public class ProgressEventArgs : EventArgs { public int Percentage { get; } public string Message { get; } public ProgressEventArgs(int percentage, string message) { Percentage = percentage; Message = message; } } public class Downloader { public event EventHandler<ProgressEventArgs> ProgressChanged; public void ReportProgress(int percent, string msg) { ProgressChanged?.Invoke(this, new ProgressEventArgs(percent, msg)); } }
C. public class ProgressEventArgs : EventArgs { public int Percentage; public string Message; } public class Downloader { public event EventHandler<ProgressEventArgs> ProgressChanged; public void ReportProgress(int percent, string msg) { ProgressChanged(this, new ProgressEventArgs { Percentage = percent, Message = msg }); } }
D. public class ProgressEventArgs : EventArgs { public int Percentage { get; set; } public string Message { get; set; } } public class Downloader { public event EventHandler<ProgressEventArgs> ProgressChanged; public void ReportProgress(int percent, string msg) { ProgressChanged(this, new ProgressEventArgs { Percentage = percent, Message = msg }); } }

Solution

  1. Step 1: Define immutable custom event args with constructor

    public class ProgressEventArgs : EventArgs { public int Percentage { get; } public string Message { get; } public ProgressEventArgs(int percentage, string message) { Percentage = percentage; Message = message; } } public class Downloader { public event EventHandler<ProgressEventArgs> ProgressChanged; public void ReportProgress(int percent, string msg) { ProgressChanged?.Invoke(this, new ProgressEventArgs(percent, msg)); } } defines ProgressEventArgs inheriting from EventArgs with readonly properties set via constructor, which is a good practice.
  2. Step 2: Raise event safely with null check

    public class Downloader { public event EventHandler<ProgressEventArgs> ProgressChanged; public void ReportProgress(int percent, string msg) { ProgressChanged?.Invoke(this, new ProgressEventArgs(percent, msg)); } } uses null-conditional operator ?. to safely raise the event with the new event args instance.
  3. Final Answer:

    public class ProgressEventArgs : EventArgs { public int Percentage { get; } public string Message { get; } public ProgressEventArgs(int percentage, string message) { Percentage = percentage; Message = message; } } public class Downloader { public event EventHandler<ProgressEventArgs> ProgressChanged; public void ReportProgress(int percent, string msg) { ProgressChanged?.Invoke(this, new ProgressEventArgs(percent, msg)); } } -> Option B
  4. Quick Check:

    Immutable EventArgs via ctor + safe ?.Invoke [OK]
Hint: Use constructor for EventArgs properties and null-check event before invoke [OK]
Common Mistakes:
  • Not inheriting from EventArgs
  • Using wrong event handler delegate type
  • Invoking event without null check
  • Using public fields instead of properties
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard