tags:

views:

267

answers:

5

Is there a bit of syntactic sugar for prefixing data to the beginning of a string in a similar way to how += appends to a string?

+19  A: 

Just use:

x = "prefix" + x;

There's no compound assignment operator that does this.

Jon Skeet
Thanks Jon (Tony). I've taken your comments below into account also.
Jamie Dixon
+17  A: 
sorry = "nope, " + sorry;
Kaleb Brasee
A: 

These are methods from the FCL that can be used to merge strings, without having to use any concatenation operator. The + and += operators are prone to using a lot of memory when called repeatedly (i.e. a loop) because of the nature of strings and temp strings created. (Edit: As pointed out in comments, String.Format is often not an efficient solution either)

It's more of a syntactic alternative than sugar.

string full = String.Format("{0}{1}{2}", "prefix", "main string", "last string");

^ More info on String.Format at MSDN.

Edit: Just for two strings:

string result = string.Concat("prefix", "last part");

^ More info on String.Concat.

John K
Using String.Format repeatedly would be just as problematic. Using String.Concat is more efficient than using String.Format, to just concatenate strings. Concatenation in a loop is likely to be better using a StringBuilder, not String.Format.
Jon Skeet
Using String.Format this way is very inefficient. The CPU use is much worse, and it also still wastes RAM. You want String.Concat instead: string full = String.Concat("prefix", "main string", "last string"). You can also pass String.Concat a string[] that you built in a loop (eg you can build a List<string>, then ToArray() it). This results in the very least memory usage of all because it allocates only the space needed to store the resulting string. Both "+" and String.Format on average allocate about 30% more RAM than needed. This is important only when dealing with large strings.
Ray Burns
Tony, I added the Concat method to the String members example.
John K
Ray I added an edit.
John K
Thanks guys. Very helpful.
Jamie Dixon
+7  A: 

You could always write an extension method:

public static class StringExtensions{

    public static string Prefix(this string str, string prefix){
        return prefix + str;
    }

}

var newString = "Bean".Prefix("Mr. ");

It's not syntactic sugar, but easy nonetheless. Although it is not really any simpler than what has already been suggested.

Josh
+7  A: 

There is no =+ operator in C#, but thankfully OO comes to the rescue here:

string value = "Jamie";
value = value.Insert(0, "Hi ");

For more info on string.Insert: http://msdn.microsoft.com/en-us/library/system.string.insert.aspx

I would agree that a = b + a seems the most sensible answer here. It reads much better than using string.Insert that's for sure.

NickGPS
Cheers Nick. I decided to go with the String.Concat method in the end.
Jamie Dixon