Is it possible to include a C# variable in a string variable without using a concatenator?

前端 未结 14 1758
遥遥无期
遥遥无期 2021-02-14 07:02

Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In

14条回答
  •  梦谈多话
    2021-02-14 07:30

    Or combined:

    Console.WriteLine("The date is {0}", DateTime.Now);
    

    Extra info (in response to BrandonZeider):

    Yep, it is kind-a important for people to realize that string conversion is automatically done. Manually adding ToString is broken, e.g.:

    string value = null;
    Console.WriteLine("The value is '{0}'", value); // OK
    Console.WriteLine("The value is '{0}'", value.ToString()); // FAILURE
    

    Also, this becomes a lot less trivial once you realize that the stringification is not equivalent to using .ToString(). You can have format specifiers, and even custom format format providers... It is interesting enough to teach people to leverage String.Format instead of doing it manually.

提交回复
热议问题