Free mag vol1 | Page 271

CHAPTER 5  UNDERSTANDING ENCAPSULATION p1.X = 10; p1.Y = 10; r.TopLeft = p1; Point p2 = new Point(); p2.X = 200; p2.Y = 200; r.BottomRight = p2; While you might feel object initialization syntax can take a bit of getting used to, once you get comfortable with the code, you’ll be quite pleased at how quickly you can establish the state of a new object with minimal fuss and bother. To wrap up this chapter, allow me to close with three bite-sized topics that will round out your understanding of building well-encapsulated classes: constant data, read-only fields, and partial class definitions.  Source Code The ObjectInitilizers project can be found under the Chapter 5 subdirectory. Working with Constant Field Data C# offers the const keyword to define constant data, which can never change after the initial assignment. As you might guess, this can be helpful when you are defining a set of known values for use in your applications that are logically connected to a given class or structure. Assume you are building a utility class named MyMathClass that needs to define a value for the value PI (which you will assume to be 3.14). Begin by creating a new Console Application project named ConstData. Given that you would not want to allow other developers to change this value in code, PI could be modeled with the following constant: namespace ConstData { class MyMathClass { public const double PI = 3.14; } class Program { static void Main(string[] args) { Console.WriteLine("***** Fun with Const *****\n"); Console.WriteLine("The value of PI is: {0}", MyMathClass.PI); // Error! Can't change a constant! // MyMathClass.PI = 3.1444; } } Console.ReadLine(); } 207