Hello everyone, in the process of learning C #, a question arose regarding the cleaning of the textBox with WinForms. On open spaces there are different ways:

textBox.Text = null; textBox.Clear(); textBox.Text = ""; 

Which is more appropriate to use? Maybe there are some features? Thank.

  • Where does this textbox come from: WinForms, WPF, something else? | In general, if you follow the MVC / MVVM patterns, etc., then the control should be tied to the model (the data model property). Therefore, you need to clear this property, and the control (in our case, a textbox) will clear itself. - Alexander Petrov
  • textbox with WinForms - mygedz

2 answers 2

My opinion - do not care how you will clean) any of these methods.

but since there is a textBox.Clear(); function textBox.Clear(); then I would use it. At least - because the record is shorter and the code is more readable.

    If we trace the call chain of the Text 1 , 2 , 3 property, we will see the following code:

     if (value == null) { value = ""; } 

    That is, null cannot be set to this property, anyway, an empty string will be assigned. Therefore, the textBox.Text = null; method textBox.Text = null; disappears.

    Tracing the call chain of the Clear method 4 , 5 , we see:

     public void Clear() { Text = null; } 

    Suddenly, the assignment is null . Hmm, why not immediately assign "" ? ..

    In general, use the method, since it is there and calling it a couple of characters shorter.


    Modern applications typically use data binding . We do not work directly with graphic controls. Values ​​in them change indirectly.

    An example is a cumbersome one, but once I took it upon myself to explain, I’ll finish it.

    Suppose we have a class that describes a person who has a name (add other properties yourself). In order for instances of this class to participate in two-way data binding, you need to implement the INotifyPropertyChanged interface.

     class Person : INotifyPropertyChanged { private string _name; public string Name { get => _name; set { if (_name != value) { _name = value; NotifyPropertyChanged(); } } } private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } 

    Create an instance of this class and bring it to the existing textbox:

     var person = new Person { Name = "Bob" }; textBox.DataBindings.Add( nameof(TextBox.Text), person, nameof(Person.Name), false, DataSourceUpdateMode.OnPropertyChanged); 

    Now to clear the textbox, just clear the bound property:

     person.Name = ""; 

    If you create large serious applications, you will inevitably encounter data binding and INotifyPropertyChanged, so you will have to master them.