0

I have a mini project im working on in c#. I'm fairly new to c# and was wondering why I should use a placeholder {0} instead of a +. Are there any differences? Any benefit to using one over the other?

Heres an example-

 public void DisplayMessage()
  {
    Console.WriteLine("Student Name:"+ Name); // Why not this
    Console.WriteLine("Studnt Age: {0}", Age);// instead of this?
  }

Thank you

1 Answers1

2

Formatted string is clearer than adding strings, especially when you have more than two parameters.

static readonly string UrlFormat = "{0}://{1}/{2}?{3}";  //the format can be reused
var url = string.Format(UrlFormat, scheme, host, path, query);
var anotherUrl = string.Format(UrlFormat, scheme2, host2, path2, query2);
var bad = scheme3 + "://" + host3 + "/" + path3 + "?" + query3;  

By the way in C#6 the format can be more pretty:

var urlUsingNewFeature = $"{scheme}://{host}/{path}?{query}";

You can see the maintenance cost between them.

The performance The only advantage of adding strings is that when you adding two strings, it's faster than string formatting.

"Student Name: " + name

is a little faster than

string.Format("Student Name: {0}", name)

I did the benchmark before, adding <=3 strings is faster than using string.Format. But IMO you still should use string.Format, the tiny performance improvement is not that important.

Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
  • Yeah the end user wont notice a difference anyway.. – user3793369 Feb 29 '16 at 02:33
  • 1
    @user3793369 But as a backend developer, we should care about those won't be seen by users. Code style and re-usage is quite important. – Cheng Chen Feb 29 '16 at 02:36
  • @user3793369 Maybe, but still you better stick to the best practices – Konstantin Chernov Feb 29 '16 at 02:50
  • @user3793369 As a developer staring at that line of code at 10pm following a bad deployment and lots of emergency meetings and triage. I can tell you that the difference is night and day. That is either leaving work during night, or day. – Aron Feb 29 '16 at 04:19