Consider the following extension to a WPF TextBox
:
public static void Parse<T>(this TextBox textBox, Func<string, T> parser)
{
try
{
T value = parser(textBox.Text);
textBox.Text = value.ToString();
}
catch
{
textBox.Text = default(T).ToString();
}
}
That can be used like so:
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
((TextBox)sender).Parse(double.Parse);
}
My question is: can the extension method be updated/modified so that I can call ((TextBox)sender).Parse(double)
instead of ((TextBox)sender).Parse(double.Parse)
?
EDIT
The extension method is meant to be very easily used to make sure that the user set, for example, a double
or int
value inside a TextBox
. The idea is to use the method like so:
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
((TextBox)sender).Parse(double); // make sure the input is a double
//or
((TextBox)sender).Parse(int); // make sure the input is a int
}
What goes inside the extension method doesn't really matter, as long as it works, but I want a minimalist code.
Perhaps a better name for the method would be something like ParseTo()
, or better yet, Validate()
, as said in the comments.