I am bit confused between the below three ways to clear the contents of a textbox. I am working with WPF and found All are working, but I am unable to find the difference.
If not going really deep:
Clear: remove content from TextBox and may be delete resources allocated with it
public void Clear()
{
using (this.TextSelectionInternal.DeclareChangeBlock())
{
this.TextContainer.DeleteContentInternal(this.TextContainer.Start, this.TextContainer.End);
this.TextSelectionInternal.Select(this.TextContainer.Start, this.TextContainer.Start);
}
}
Assigning empty string (because string.Empty and "" are equal) to Text property just assign empty string to attached property TextBox.TextProperty:
public string Text
{
get
{
return (string) this.GetValue(TextBox.TextProperty);
}
set
{
this.SetValue(TextBox.TextProperty, (object) value);
}
}
It appears that it is doing quite some additional stuff, like checking for the origin of the change, bindings, updating caret position and updating/clearing undo. Most of which is likely not needed when assigning an empty string.
/// <summary>
/// Callback for changes to the Text property
/// </summary>
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBox textBox = (TextBox)d;
bool inReentrantChange = false;
int savedCaretIndex = 0;
if (textBox._isInsideTextContentChange)
{
// Ignore property changes that originate from OnTextContainerChanged,
// unless they contain a different value (indicating that a
// re-entrant call changed the value)
if (textBox._newTextValue != DependencyProperty.UnsetValue)
{
// OnTextContainerChanged calls
// SetCurrentDeferredValue(TextProperty, deferredTextReference)
// Usually the DeferredTextReference will appear in the new entry
if (textBox._newTextValue is DeferredTextReference)
{
if (e.NewEntry.IsDeferredReference &&
e.NewEntry.IsCoercedWithCurrentValue &&
e.NewEntry.ModifiedValue.CoercedValue == textBox._newTextValue)
{
return;
}
}
// but if the Text property is data-bound, the deferred reference
// gets converted to a real string; during the conversion (in
// DeferredTextReference.GetValue), the TextBox updates _newTextValue
// to be the string.
else if (e.NewEntry.IsExpression)
{
object newValue = e.NewEntry.IsCoercedWithCurrentValue
? e.NewEntry.ModifiedValue.CoercedValue
: e.NewEntry.ModifiedValue.ExpressionValue;
if (newValue == textBox._newTextValue)
{
return;
}
}
}
// If we get this far, we're being called re-entrantly with a value
// different from the one set by OnTextContainerChanged. We should
// honor this new value.
inReentrantChange = true;
savedCaretIndex = textBox.CaretIndex;
}
// CoerceText will have already converted null -> String.Empty,
// but our default CoerceValueCallback could be overridden by a
// derived class. So check again here.
string newText = (string)e.NewValue;
if (newText == null)
{
newText = String.Empty;
}
textBox._isInsideTextContentChange = true;
try
{
using (textBox.TextSelectionInternal.DeclareChangeBlock())
{
// Update the text content with new TextProperty value.
textBox.TextContainer.DeleteContentInternal((TextPointer)textBox.TextContainer.Start, (TextPointer)textBox.TextContainer.End);
textBox.TextContainer.End.InsertTextInRun(newText);
// Collapse selection to the beginning of a text box
textBox.Select(savedCaretIndex, 0);
}
}
finally
{
//
if (!inReentrantChange)
{
textBox._isInsideTextContentChange = false;
}
}
// We need to clear undo stack in case when the value comes from
// databinding or some other expression.
if (textBox.HasExpression(textBox.LookupEntry(TextBox.TextProperty.GlobalIndex), TextBox.TextProperty))
{
UndoManager undoManager = textBox.TextEditor._GetUndoManager();
if (undoManager != null)
{
if (undoManager.IsEnabled)
undoManager.Clear();
}
}
}
Well.. 1st a warning, this answer have that potential to be outside of the current consensus of most developers here but here goes :) try to read it till the end.
These two (and even additional one I included) are exactly the same:
txtUserName.Text = "";
txtUserName.Text = string.Empty;
txtUserName.Text = null;
Even if the assembly in debug configuration might come out a bit different, I am positive that in the release mode which is more optimized they will compile to the exact same assembly.
In case they are not coming out the same - this implies a degraded ability of the complier to translate in the most optimal translation the code agenda of this case, or in other words.. in other languages this might come as the same assembly and from an academic vision of it - it should come out as the same assembly. but not every complier care that much of the academic view of things :)
Regarding the third dude txtUserName.Clear()
this is a different case, I assume just like you that the inner implementation of this method actually do or simply use one of those three assignments..
(and as others already mentioned it do even more beyond just removing the chars from the text)
However, if you think object oriented - assume someone want to create a special textbox which includes for example more things to clear in it - for him it will be very convenient to have that 'Clear' method to override.. and if you used the clear method - you don't change your code when you change from the basic textbox to that new custom/special texbox.
So to sum it up - if you are to use the control, you should use its methods and that means using that 'Clear()' method will be more suitable when you want to clear it especially if one day in the future you would want to replace that textbox with a custom textbox of your own. so at least grammatically it is the better choice..
But yes, it will inflict performance if all you wanted is simply to remove the characters from the text property..
Here is a small program to test the efficiency of each under WPF.
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Name="txtbx1" Grid.Row="0"/>
<TextBox Name="txtbx2" Grid.Row="1"/>
<TextBox Name="txtbx3" Grid.Row="2"/>
<TextBox Name="txtbx4" Grid.Row="3"/>
</Grid>
using System;
using System.Windows;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DateTime oldTime, newTime;
TimeSpan delta;
var iterations = 100000;
#region Test performance 1
oldTime = DateTime.Now;
for (var i = 0; i < iterations; i++)
txtbx1.Text = "";
newTime = DateTime.Now;
delta = newTime - oldTime;
txtbx1.Text = delta.Milliseconds.ToString();
#endregion
#region Test performance 2
oldTime = DateTime.Now;
for (var i = 0; i < iterations; i++)
txtbx2.Text = string.Empty;
newTime = DateTime.Now;
delta = newTime - oldTime;
txtbx2.Text = delta.Milliseconds.ToString();
#endregion
#region Test performance 3
oldTime = DateTime.Now;
for (var i = 0; i < iterations; i++)
txtbx3.Text = null;
newTime = DateTime.Now;
delta = newTime - oldTime;
txtbx3.Text = delta.Milliseconds.ToString();
#endregion
#region Test performance 4
oldTime = DateTime.Now;
for (var i = 0; i < iterations; i++)
txtbx4.Clear();
newTime = DateTime.Now;
delta = newTime - oldTime;
txtbx4.Text = delta.Milliseconds.ToString();
#endregion
}
}
}
Those were the results I got: 43, 40, 73, 443
And it is consistent - the first two are about the same +/- a mini-second or two, the third is always slightly longer and the last one is definitely longer than all others.
I think that that is as deep as it gets :)
Some say String.Empty is faster than "" however String.EMpty is Static member that is initialized to ""
When we call String.Empty
the IL
makes call to
mscorlib.dll
IL_0007: ldsfld string [mscorlib]System.String::Empty
Whereas for "" it does not
IL_001a: ldstr ""
SO logically it would make more sense that "" is more efficient than String.Empty