Equivalent + = for prefix

Is there a bit of syntactic sugar for prefixing data at the beginning of a line, similar to how + = joins a line?

+6
string c #
source share
5 answers

Just use:

x = "prefix" + x; 

There is no such compound assignment operator that does this.

+20
source share
 sorry = "nope, " + sorry; 
+17
source share

You can 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 is not syntactic sugar, but nonetheless light. Although in reality it is not as simple as has already been proposed.

+7
source share

In C # there is no operator = +, but, fortunately, OO comes to the rescue:

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

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

I would agree that a = b + a seems to be the most reasonable answer here. It reads a lot better than using string.Insert for sure.

+7
source share

These are methods from FCL that can be used to concatenate strings without using any concatenation operator. The + and + = operators tend to use a large amount of memory for repeated calls (i.e., in a loop) due to the nature of the lines and time lines being created. ( Edit: As pointed out in the comments, String.Format is often not an effective solution)

This is a syntactic alternative rather than sugar.

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

^ More information about String.Format on MSDN .

Edit: For only two lines:

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

^ More information about String.Concat .

0
source share

All Articles