Given the following classes:
public abstract class ValueBase
{
public new abstract string ToString();
}
public class EmailAddress : ValueBase
{
public MailAddress MailAddress { get; }
public EmailAddress([NotNull] string address)
{
MailAddress = new MailAddress(address);
}
public override string ToString()
{
return MailAddress.Address;
}
}
Why does:
var email = new EmailAddress("[email protected]");
string emailString1 = $"{email}";
string emailString2 = email.ToString();
return a string of the type name (Namespace.EmailAddress
), not the overridden ToString method ([email protected]
)?
Interpolation works as expected since your classes do not override Object.ToString()
. ValueBase
defines a new method that hides Object.ToString
instead of overriding it.
Simply remove ToString
from ValueBase
. In this case Email.Address
will override Object.ToString
correctly, and interpolation will return the desired result.
Specifically, changing ValueBase to this:
public abstract class ValueBase
{
}
Makes the test code
var email = new EmailAddress("[email protected]");
string emailString1 = $"{email}";
return [email protected]
UPDATE
As people suggested, the base ToString()
method could be added to force implementers to implement a custom ToString
method in their classes. This can be achieved by defining an abstract override
method.
public abstract class ValueBase
{
public abstract override string ToString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With