-2

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
Scover
  • 93
  • 9
  • 5
    If you don't have multiple textboxes all using the same event handler code, I'd say access it directly. – ProgrammingLlama Aug 31 '21 at 09:53
  • This is what i was thinking, but it may not be the case in the future. Maybe i can access it directly if the control's name is in the method's name, i.e `TextBox1_Validating` – Scover Aug 31 '21 at 10:03
  • 3
    Basically opinion-based, but It may depends if you expect the sender to be textbox1 and always it, or if, for example, you assign the event handler to multiple controls, thus you need to cast sender. Also *to be scrupulous* use the latter way to check type as well as not null. Passing null as sender when calling directly the method, or any other thing, to control the handler behavior, is perfectly legal. –  Aug 31 '21 at 10:04
  • I agree, and direct acess is also more readable – Scover Aug 31 '21 at 10:12

2 Answers2

0
  • 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.

Scover
  • 93
  • 9
-2

I always access the control directly

if(textbox1.text==string.Empty)
{//doSomething;}
  • 1
    Please add further details to expand on your answer, such as working code or documentation citations. – Community Aug 31 '21 at 10:18