1

Possible Duplicate:
When is it better to use String.Format vs string concatenation?

What is the best practices when using String.Format for C#. I always get confused here because it just seems way simpler to do operations like this

    private string _ExecuteCommand(string cmd)
    {
        // Start the child process.
        Process p = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo();

        // Redirect the output stream of the child process.
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = String.Format("/C {0}", cmd); // prevents the command line from staying open after execution

        //... you get the idea
    }

Is there a particular advantage over using the String.Format vs just string concatenation? In other words, i could just do this instead...,

startInfo.Arguments = "/C " + cmd; // prevents the command line from staying open after execution

I would like to continue to persue quality code, but i do not know when its quality to use String.Format. If anyone has any suggestions i would appreciate it.

Community
  • 1
  • 1
ThePrimeagen
  • 4,462
  • 4
  • 31
  • 44

3 Answers3

1

In this case, I'd go with the straight concatenation; The MS Certification articles suggest simple concatenation for just two strings.

If your variable was a DateTime object (for example) and you needed a particular format, then I would use String.Format.

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
0

String.Format will help you when you need to translate your app into multiple languages, or cope with different environment. If you use it string.format from the start you put yourself in a better place as it will be much easier to put all your strings into resource files.

In your example if you use string.format and then choose to store the Start Info string in a resource file, you could provide separate resource files for different environments to support MAC, windows and Linux without needing to change the code.

JonAlb
  • 1,702
  • 10
  • 14
0

String.Format is more readable while string concatenation is faster. String.Format uses an inner StringBuilder to format the string, so it is a bit slower but more robust.

Balazs Tihanyi
  • 6,659
  • 5
  • 23
  • 24