Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation in C# 6 and overridden ToString()

Tags:

string

c#

c#-6.0

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])?

like image 211
Darbio Avatar asked Apr 13 '16 09:04

Darbio


1 Answers

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();
}
like image 55
Panagiotis Kanavos Avatar answered Sep 30 '22 19:09

Panagiotis Kanavos