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