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:
toString() method of class Foo is not overridden, you will inherit the default . toString() from the Object class.
In conclusion, it's a good idea to override toString() , as we get proper and customized output when an object is used.
When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.
Use the implicit conversion operator in C# When you use implicit or explicit conversion operators, you don't have to write cumbersome methods to convert an instance of one type to another.
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.
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