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

前端 未结 14 1752
遥遥无期
遥遥无期 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:26
    string.Format("The date is {0}", DateTime.Now.ToString())
    
    0 讨论(0)
  • 2021-02-14 07:30

    Based on the great answer of @JesperPalm I found another interesting solution which let's you use a similar syntax like in the normal string.Format method:

    public static class StringExtensions
    {
        public static string Replace<T>(this string text, T values)
        {
            var sb = new StringBuilder(text);
            var properties = typeof(T)
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .ToArray();
    
            var args = properties
                .Select(p => p.GetValue(values, null))
                .ToArray();
    
            for (var i = 0; i < properties.Length; i++)
            {
                var oldValue = string.Format("{{{0}", properties[i].Name);
                var newValue = string.Format("{{{0}", i);
    
                sb.Replace(oldValue, newValue);
            }
    
            var format = sb.ToString();
    
            return string.Format(format, args);
        }
    }
    

    This gives you the possibility to add the usual formatting:

    var hello = "Good morning";
    var world = "Mr. Doe";
    var s = "{hello} {world}! It is {Now:HH:mm}."
        .Replace(new { hello, world, DateTime.Now });
    
    Console.WriteLine(s); // -> Good morning Mr. Doe! It is 13:54.
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-14 07:32
    string output = "the date is $d and time is $t";
    output = output.Replace("$t", t).Replace("$d", d);  //and so on
    
    0 讨论(0)
  • 2021-02-14 07:32

    Since C# 6.0 you can write string "The title is \{title}" which does exactly what you need.

    0 讨论(0)
  • 2021-02-14 07:37

    string.Format (and similar formatting functions such as StringBuilder.AppendFormat) are the best way to do this in terms of flexibility, coding practice, and (usually) performance:

    string s = string.Format("The date is {0}", d);
    

    You can also specify the display format of your DateTime, as well as inserting more than one object into the string. Check out MSDN's page on the string.Format method.

    Certain types also have overloads to their ToString methods which allow you to specify a format string. You could also create an extension method for string that allows you to specify a format and/or parse syntax like this.

    0 讨论(0)
提交回复
热议问题