Free mag vol1 | Page 168

CHAPTER 3  CORE C# PROGRAMMING CONSTRUCTS, PART I sb.Replace("2", " Invisible War"); Console.WriteLine(sb.ToString()); Console.WriteLine("sb has {0} chars.", sb.Length); Console.WriteLine(); } Here, we have constructed a StringBuilder set to the initial value "**** Fantastic Games ****". As you can see, we are appending to the internal buffer and are able to replace or remove characters at will. By default, a StringBuilder is only able to initially hold a string of 16 characters or fewer (but will expand automatically if necessary); however, this default starting value can be changed via an additional constructor argument. // Make a StringBuilder with an initial size of 256. StringBuilder sb = new StringBuilder("**** Fantastic Games ****", 256); If you append more characters than the specified limit, the StringBuilder object will copy its data into a new instance and grow the buffer by the specified limit.  Source Code The FunWithStrings project is located under the Chapter 3 subdirectory. Narrowing and Widening Data Type Conversions Now that you understand how to work with intrinsic C# data types, let’s examine the related topic of data type conversion. Assume you have a new Console Application project named TypeConversions that defines the following class: class Program { static void Main(string[] args) { Console.WriteLine("***** Fun with type conversions *****"); // Add two shorts and print the result. short numb1 = 9, numb2 = 10; Console.WriteLine("{0} + {1} = {2}", numb1, numb2, Add(numb1, numb2)); Console.ReadLine(); } static int Add(int x, int y) { return x + y; } } Notice that the Add() method expects to be sent two int parameters. However, the Main() method is, in fact, sending in two short variables. While this might seem like a complete and total mismatch of data types, the program compiles and executes without error, returning the expected result of 19. 102