Skip to main content

Posts

Showing posts from May, 2007

Performance improvement with StringBuilder class

Often we do large string concatenation in our code without giving a thought to performance. Consider following example of string concatenation. string s1 = "orange"; string s2 = "red"; s1 += s2; System.Console.WriteLine(s1); // outputs "orangered" s1 = s1.Substring(2, 5); System.Console.WriteLine(s1); // outputs "ange r" String objects are immutable, meaning that they cannot be changed once they have been created. Methods that act on strings actually return new string objects. In the previous example, when the contents of s1 and s2 are concatenated to form a single string, the two strings containing "orange" and "red" are both unmodified. The += operator creates a new string that contains the combined contents. The result is that s1 now refers to a different string altogether. A string containing just "orange" still exists, but is no longer referenced when s1 is concatenated. Therefore, for performance reasons, lar

Strings

The @ Symbol The @ symbol tells the string constructor to ignore escape characters and line breaks. The following two strings are therefore identical: string p1 = "\\\\My Documents\\My Files\\"; string p2 = @"\\My Documents\My Files\"; // Copy one character of the string (not possible with a System.String) sb[0] = sb[9]; System.Console.WriteLine(sb); // displays 9123456789 } }

Method returning multiple values

If you want methods to return more than one value, declare the parameters as OUT or REF. Methods with OUT or REF are identical at compile time but different at run time. Hence you cannot overload a method one with OUT where as other with REF. You can overload method by declaring one with OUT or REF and another without it. The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. Same applied for REF For example: class OutExample { static void Method(out int i, out int j) { i = 44; j= 22; } static void Main() { int value1; int value2; Method(out value1, out value2); // value1 is now 44 //value2 is now 22 } } Although variables passed as an OUT arguments need not be initialized prior to being passed, the calling method is required to assign a value before the met