Web design company - CHAPTER 3 72 C# LANGUAGE FUNDAMENTALS Is
CHAPTER 3 72 C# LANGUAGE FUNDAMENTALS Is That aMemory Leak? If you have a background in C++, you may be alarmed by the previous code samples. Specifically, notice how the Main() method of the previous HelloClass type has no logic that explicitly destroys the c1 and c2 references. This is not a horrible omission, but the way of .NET. Like Visual Basic and Java developers, C# programmers never explicitly destroy a managed object. The .NET garbage collector frees the allocated memory automatically, and therefore C# does not support a delete keyword. Chapter 5 examines the garbage collection process in more detail. Until then, just remember that the .NET runtime environment automatically destroys the managed objects you allocate. Defining an Application Object Currently, the HelloClass type has been constructed to perform two duties. First, the class defines the entry point of the application (the Main() method). Second, HelloClass maintains a point of field data and a few constructors. While this is all well and good, it may seem a bit strange (although syntactically well-formed) that the static Main() method creates an instance of the very class in which it was defined: class HelloClass { … public static int Main(string[] args) { HelloClass c1 = new HelloClass(); … } } Many of my initial examples take this approach, just to keep focused on illustrating the task at hand. However, amore natural design would be to refactor the current HelloClass type into two distinct classes: HelloClass and HelloApp. When you build C# applications, it becomes quite common to have one type functioning as the application object (the type that defines the Main() method) and numerous other types that constitute the application at large. In OO parlance, this is termed the separation of concerns. In a nutshell, this design principle states that a class should be responsible for the least amount of work. Thus, we could reengineer the current program into the following (notice that a new member named PrintMessage() has been added to the HelloClass type): class HelloClass { public string userMessage; public HelloClass() { Console.WriteLine(”Default ctor called!”); } public HelloClass(string msg) { Console.WriteLine(”Custom ctor called!”); userMessage = msg; } public void PrintMessage() { Console.WriteLine(”Message is: {0}”, userMessage); } }
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.