Question

In some C# code I'm working on, a DateTime object (dt) is concatenated with two strings:

string test = "This is a test " + dt + "...Why does this work?"

This doesn't raise a compile error and is working just fine. My question: why is this legal? Is this specific only to DateTime objects, or to any objects overriding the ToString() method?

Was it helpful?

Solution 2

This is an implicit type conversion of a parameter that is performed because of the + operator.

It is talked about in the specification here: http://msdn.microsoft.com/en-us/library/aa691375%28v=vs.71%29.aspx

OTHER TIPS

It compiles because the C# specifications state that there is an overload of the + operator with the following signature:

operator + (string str, object obj)

You are providing a string and an expression that is implicitly convertable to object, so this operator and no others matches your arguments, and it compiles.

Internally this operator's implementation will call string.Concat, which will convert the object into a string using its ToString method (assuming it is not null) and then concat the strings as strings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top