Here is a shortest possible syntax for replacing whitespaces with null
and throwing an exception where it is not allowed:
public class Name
{
string _first;
public string First
{
get => _first;
set => _first = (Optional)value;
}
string _middle;
public string Middle
{
get => _middle;
set => _middle = (Required)value;
}
}
Where:
public class Optional
{
public static explicit operator Optional(string text) => new Optional(text);
public static implicit operator string(Optional optional) => optional.Text;
Optional(string text) => Text = IsNullOrWhiteSpace(text) ? null : text;
string Text { get; }
}
And:
public class Required
{
public static explicit operator Required(string text) => new Required((Optional)text);
public static implicit operator string(Required required) => required.Text;
Required(string text) => Text = text ?? throw new FormatException();
string Text { get; }
}
P.S. Value modification on property assignment is not recommended, but could be very handy sometimes :)