Why don't you define an abstract
class with the following two methods:
- One which can convert an
object
tostring
- Another which can convert an
object
todouble
public abstract class FromObjectConverter
{
protected double ToDouble(object value)
=> double.TryParse(value as string, out var x) ? x : double.NaN;
protected string ToString(object value)
=> value is double x ? x.ToString("f3") : string.Empty;
}
With this class in our hand the two concrete converter classes are just simple wrappers
public sealed class StringToDoubleConverter : FromObjectConverter, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> ToDouble(value);
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> ToString(value);
}
public sealed class DoubleToStringConverter : FromObjectConverter, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> ToString(value);
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> ToDouble(value);
}
Or if you want to avoid inheritance then define the FromObjectConverter
class and its methods as static
.