String concatenation in C# with DateTime objects: why is my code legal? [duplicate]

StackOverflow https://stackoverflow.com/questions/22973931

  •  30-06-2023
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책 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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top