Let's say I have an event handler to validate the text entered in my TextBox
control.
- Should i cast the
sender
parameter ?
((TextBox)sender).Text
- Or access the control directly ?
textBox1.text
Let's say I have an event handler to validate the text entered in my TextBox
control.
sender
parameter ?((TextBox)sender).Text
textBox1.text
Casting sender is bad from a type-safety standpoint, since you have no compile-time guarantee that sender is of the expected type.
Referencing an external variable is a viable solution in most situations, but it could result in unnecessary closures when subscribing with a local function or a lambda expression:
public Class1
{
public Class1(string argument)
{
// This is a closure!
MyEvent += (s, e) => Console.WriteLine(argument)
}
}
So there's no one-size-fits-all solution here. It depends on the problem you're trying to solve.
A definitive solution would be for the API to use the Type-safe event handler pattern (see question), so you get the right type for sender.
I always access the control directly
if(textbox1.text==string.Empty)
{//doSomething;}