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

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

  •  30-06-2023
  •  | 
  •  

Pergunta

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?

Foi útil?

Solução 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

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top