What if your events could tell you the full story, not just that something happened?
Why Custom event arguments in C Sharp (C#)? - Purpose & Use Cases
Imagine you have a button in your app, and when someone clicks it, you want to know not just that it was clicked, but also some extra details like which user clicked it or what time it happened.
If you try to handle this by just using simple events without extra information, you end up writing lots of extra code to share those details separately. It gets messy, confusing, and easy to make mistakes.
Custom event arguments let you package all the extra details into one neat object. When the event happens, you send this object along, so the event handler gets everything it needs in one place, clean and simple.
event EventHandler ButtonClicked;
// No extra info passed with eventclass ButtonClickedEventArgs : EventArgs { public string UserName; }
event EventHandler<ButtonClickedEventArgs> ButtonClicked;It makes your events powerful and clear by carrying all the important details right when they happen.
In a chat app, when a message is sent, a custom event argument can include the message text, sender name, and timestamp, so the app knows exactly what happened.
Manual event handling lacks detailed info and gets messy.
Custom event arguments bundle extra data neatly with the event.
This makes event handling clearer, easier, and less error-prone.
Practice
EventArgs in C#?Solution
Step 1: Understand the role of
TheEventArgsEventArgsclass is used to pass data with events. Creating a custom class inheriting from it allows adding extra information.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.Final Answer:
To send additional data with an event when it is raised. -> Option CQuick Check:
Custom EventArgs = Extra event data [OK]
- Thinking custom EventArgs replace EventHandler delegate
- Believing custom EventArgs stop event repetition
- Assuming custom EventArgs handle exceptions automatically
MyEventArgs with a string property Message?Solution
Step 1: Check inheritance from
The custom event argument class must inherit fromEventArgsEventArgsto be used properly in events.Step 2: Verify property type and syntax
The propertyMessageshould be a string with get and set accessors for data storage.Final Answer:
public class MyEventArgs : EventArgs { public string Message { get; set; } } -> Option DQuick Check:
Custom EventArgs inherit EventArgs + correct property type [OK]
- Forgetting to inherit from EventArgs
- Using EventHandler as base class instead of EventArgs
- Declaring property with wrong type
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?
Solution
Step 1: Understand event raising and subscription
ThePublisherraisesOnNumberChangedevent withMyEventArgscontaining the number passed.Step 2: Check subscriber's event handler output
The subscriber prints theNumberproperty from the event args, which is set to 42.Final Answer:
Number is 42 -> Option AQuick Check:
Event raised with Number=42 prints "Number is 42" [OK]
- Assuming event is not raised or subscribed
- Confusing default values with passed values
- Mistaking event handler signature causing errors
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();Solution
Step 1: Check event invocation safety
The eventOnInfoChangedis invoked without checking if it has subscribers, so if null, it causes a runtime NullReferenceException.Step 2: Identify missing subscriber check
Before invoking, the code should check ifOnInfoChangedis not null to avoid errors.Final Answer:
OnInfoChanged event is null because no subscribers are attached. -> Option AQuick Check:
Invoke event without subscribers = NullReferenceException [OK]
- Forgetting to check event for null before invoking
- Assuming event has subscribers by default
- Confusing property initialization with event subscription
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?Solution
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)); } } definesProgressEventArgsinheriting fromEventArgswith readonly properties set via constructor, which is a good practice.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.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 BQuick Check:
Immutable EventArgs via ctor + safe ?.Invoke [OK]
- Not inheriting from EventArgs
- Using wrong event handler delegate type
- Invoking event without null check
- Using public fields instead of properties
Ready to prove it?
Pass the test and this pattern moves unknown
