Adam Smith
Adam Smith

Reputation: 659

Can/should I use implicit operator instead of overriding ToString?

I have a class that I want to easily write out to strings (e.g. for logging purposes). Can I use the implicit operator to implicitly cast the object to a string rather than overriding the ToString method?

For example, I have a Person class with Name and Age:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set;}
}

I can override ToString:

public override string ToString()
{
    return String.Format("Name: {0}, Age: {1}", this.Name, this.Age);
}

Or I could use the implicit operator:

public static implicit operator string(Person p)
{
    return String.Format("Name: {0}, Age: {1}", p.Name, p.Age);
}

Now, when passing this object to a method that expects a string, instead of

Log(Person.ToString());

I can just call

Log(Person);

I could even just call an overridden ToString in the implicit cast

public static implicit operator string(Person p)
{
    return p.ToString();
}


Is this a bad use of the implicit operator casting to String? What is best practice when requiring this functionality? I suspect that just overloading ToString will be the best practice answer, and if so I have a couple of questions then:

  1. When would I ever use the implicit cast to String?
  2. What is a best practice example of using the implicit cast to String?

Upvotes: 19

Views: 6386

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Use ToString, consider to have logger that can itself interrogate type to construct useful string representation from an object (even converting to JSON may work).

Overriding ToSTring is expected way to produce "display only" version of an instance.

Implicit conversion should be used when object somehow compatible with destination type. I.e. you may have type that represent "LastName" and have some special methods, but for most practical purposes it is a string. Person definitely does not feel like a string so implicit conversion will surprise people who look at the code later.

Note MSDN recommendation on implicit:

Use it to enable implicit conversions between a user-defined type and another type, if the conversion is guaranteed not to cause a loss of data.

Upvotes: 23

Related Questions