Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# and the NET Platform, Second Edition - Andrew Troelsen.pdf
Скачиваний:
67
Добавлен:
24.05.2014
Размер:
22.43 Mб
Скачать
architectural issues for .NET developers.

Chapter 3: C# Language Fundamentals

C# and the .NET Platform, S cond Edition

 

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

The thrust of this chapter is to introduce you to the core aspects of the C# language, including intrinsic data

This comprehensive text starts with a brief overview of the

types (both value-based and reference-based); decision and iteration constructs; boxing and unboxing

C# language and then quickly moves to key technical and

mechanisms; the role of System.Object and basic class construction techniques. Along the way, you also learn how to manipulate CLR strings, arrays, enumerations, and structures using the syntax of C#.

To illustrate these language fundamentals, you will take a programmatic look at the .NET base class

Table of Contents

libraries, and build a number of sample applications making use of various .NET namespaces. The chapter

C# and the .NET Platform, Second Edition

closes by showing you how to organize your custom types into discrete user-defined namespaces (and

Introduction

explains why you might want to do so).

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

The Anatomy of a Basic C# Class

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Like the Java language, C# demands that all program logic is contained within a type definition (recall that a

Chapter 3 - C# Language Fundamentals

type is a generic term referring to a member of the set {class, interface, structure, enumeration, delegate}).

Chapter 4 - Object-Oriented Programming with C#

Unlike C(++), it is not possible to create global functions or global points of data. In its simplest form, a C#

Chapter 5 - Exceptions and Object Lifetime

class can be defined as follows (also recall that the "using" keyword simplifies type declarations):

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

// By convention, C# files end with a *.cs file extension.

Chapter 8 - Advanced C# Type Construction Techniques using System;

Part Three - Programming with .NET Assemblies

class HelloClass

Chapter 9 - Understanding .NET Assemblies

{

Chapter 10 - Processes, AppDomains, Contexts, and'private'Thre ds

/* Main() can be declared as

Chapter if11 -youTypedesireR flection,...Late*/Binding, and Attribute-Based Programming

Part Fourpublic- Leveragingstatiche .NETintLibrMain(string[]ries args)

Chapter {12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - BuildingConsolea Better.WriteLine("HelloWindow (IntroducingWorld!");Windows Forms)

returner 0;

Chapter 14 - A B Painting Framework (GDI+)

}

Chapter 15 - Programming with Windows Forms Controls

}

Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Here, you have created a definition for an appropriately named type (HelloClass) that supports a single

Chapter 18 - ASP.NET Web Pages and Web Controls

method named Main(). Every executable C# application must contain a class defining a Main() method,

Chapter 19 - ASP.NET Web Applications

which is used to signify the entry point of the application.

Chapter 20 - XML Web Services

IndexNote Although it is technically possible (albeit unlikely) for a single C# project to contain multiple

List of Figuresclasses defining a Main() method, you must specify which type contains the Main() method to be

used as the application's entry point (via the csc.exe /main flag or, for VS .NET applications, via

List of Tables

the "Startup Object" setting of the Project Properties window). If you fail to do so, you encounter a compile-time error.

As you can see, the signature of Main() is adorned with the public and static keywords (also note the capital "M" in Main(), which is obligatory as C# is case-sensitive). Later in this chapter you are supplied with a formal definition of the "public" and "static" keywords. Until then, understand that public methods are accessible from other types, while static methods are scoped at the class level (not at an object level) and can thus be invoked without the need to first create a new object variable.

In addition to the public and static keywords, our Main() method has a single parameter, which happens to be an array of strings (string[] args). Although you are not currently bothering to manipulate this array, it is possible that this parameter can contain any number of command line arguments (you see how to access them momentarily).

The program logic of the HelloClass is within Main() itself. Here, you make use of the Console class, which is defined within the System namespace. Among its set of members is the static WriteLine(), which as you

List of Tables
List of Figures

might assume, pumps a text string to the standard console (more details on System.Console a bit later in

C# and the .NET Platform, Second Edition

this chapter):

by Andrew Troelsen ISBN:1590590554

Apress © 2003 (1200 pages)

// Pump some text to the console.

This comprehensive text starts with a brief overview of the

Console.WriteLine("Hello World!");

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

Because our Main() method has been defined as returning an integer data type, you return zero (success)

before exiting. Finally, as you can see from the HelloClass type definition, C and C++ styles comments have

Table of Contents

carried over into the C# language.

C# and the .NET Platform, Second Edition

Introduction

PartVariationsOne - Introduciong C#theandMain()the .NET PlatformMethod

Chapter 1 - The Philosophy of .NET

The previous iteration of Main() was defined to take a single parameter (an array of strings) and return an

Chapter 2 - Building C# Applications

integer data type. This is not the only possible form of Main(), however. It is permissible to construct your

Part Two - The C# Programming Language

application's Main() method using any of the following signatures (assuming it is contained within a C# class

Chapter 3 - C# Language Fundamentals

definition):

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

// No return type, array of strings as argument.

Chapter 6 - Interfaces and Collections

public static void Main(string[] args)

Chapter 7 - Callback Interfaces, Delegates, and Events

{

Chapter 8 - Advanced C# Type Construction Techniques

// Process command line arguments.

Part Three - Programming with .NET Assemblies

// Make some objects.

Chapter 9 - Understanding .NET Assemblies

}

Chapter 10 - Processes, AppDomains, Contexts, and Threads

// No return type, no arguments.

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming public static void Main()

Part Four - Leveraging the .NET Libraries

{

Chapter 12 - Object Serialization and the .NET Remoting Layer

// Make some objects.

Chapter 13 - Building a Better Window (Introducing Windows Forms)

}

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

// Integer return type, no arguments.

Chapter 16 - The System.IO Namespace

public static int Main()

Chapter{ 17 - Data Access with ADO.NET

Part Five//- WebMakeApplicationssome objectsand XML. Web Services

Chapter//18Return- ASP.NETaWebvaluePagestoandtheW bsystemCon rols.

Chapter} 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

Obviously, your choice of how to construct Main() will be based on two questions: First, do you need to process any command line parameters? If so, they will be stored in the array of strings. Next, do you want to return a value to the system when Main() has completed? If so, you need to return an integer data type rather than void.

Processing Command Line Parameters

Assume that you now wish to update HelloClass to process any possible command line parameters (I examine the details behind the {0} notation in just a bit):

// This time, check if we have been sent any command line arguments.

using System;

class HelloClass

{

public static int Main(string[] args)

{

Console.WriteLine("***** Command line args *****");

for(int x = 0; x < args.Length; x++)

 

C# and the .NET Platform, Second Edition

 

 

Console.WriteLine("Arg: {0} ", args[x]);

 

by Andrew Troelsen

ISBN:1590590554

 

Apress © 2003 (1200 pages)

 

 

Console.WriteLine("Hello World!");

 

 

This comprehensive text starts with a brief overview of the

 

return 0;

 

}

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

 

}

Table of Contents

Here, you are checking to see if the array of strings contains some number of items using the Length

C# and the .NET Platform, Second Edition

property of System.Array (as you see later in this chapter, all C# arrays actually alias the System.Array base

Introduction

type, and therefore have a common set of members). If you have at least one member in the array, you

Part One - Introducing C# and the .NET Platform

loop over each item and print the contents to the output window.

Chapter 1 - The Philosophy of .NET

ChapterSupplying2 -theBuildingargumentsC# Applicationsthemselves is equally as simple, as illustrated in Figure 3-1.

Part Two - The C# Programming Language

 

Chapter

 

Chapter

C#

Chapter

 

Chapter

 

Chapter

Events

Chapter

Techniques

Part ThreeFigure- Programming3-1: Supplyingwithand.NETprocessingAs embliescommand line arguments

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

As an alternative to the standard for loop, you may iterate over incoming string arrays using the C#

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

"foreach" keyword. This bit of syntax is fully explained later in this chapter, however here is some sample

Part Four - Leveraging the .NET Libraries

usage:

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

// Notice we have no need to check the size of the array when using 'foreach'.

Chapter 14 - A Better Painting Framework (GDI+) public static int Main(string[] args)

Chapter 15 - Programming with Windows Forms Controls

{

Chapter 16 - The System.IO Namespace foreach(string s in args)

Chapter 17 - Data Access with ADO.NET

Console.WriteLine("Arg: {0} ", s);

Part Five - Web Applications and XML Web Services

...

Chapter 18 - ASP.NET Web Pages and Web Controls

}

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Finally, be aware that you are also able to access command line arguments using the static

Index

GetCommandLineArgs() method of the System.Environment type. The return value of this method is an

List of Figures

array of strings. The first index identifies the current directory containing the application itself, while the

List of Tables

remaining elements in the array contain the individual command line arguments. For example:

// Now using System.Environment.

string[] theArgs = Environment.GetCommandLineArgs(); Console.WriteLine("Path is: {0}", theArgs[0]);

// Skip the path to the *.exe.

for(int i=1; i < theArgs.Length; i++) Console.WriteLine("Again, the args are {0}", theArgs[i]);

Simulating Command Arguments a la VS .NET

In the real world, the end user defines the command line arguments used by a given application. However, during the development cycle you may wish to simulate possible command line flags. Using VS .NET, you are able to do so by accessing the Properties dialog for your current project. Simply set the "Command Line

Arguments" textbox found under the Configuration | Debugging node (Figure 3-2).

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

of the

and

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Figure 3-2: Setting command arguments via VS .NET

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Needless to say, regardless of the technique you use to specify application arguments, you are the one in Chaptercharge8of determining- Advanced C#whichTypecommandConstructionlineTechniquesparameters your application will respond to, and what to do with

PartthemThreeonce- Programmingthe end user haswithsupplied.NET Assembliesthem.

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Creating Objects:C# and theConstructor.NET Platform, SecondBasicsEdition

by Andrew Troelsen

ISBN:1590590554

Now that you have the role of Main() under your belt, let's move on to the topic of object construction. All

Apress © 2003 (1200 pages)

object-oriented languages make a clear distinction between classes and objects. A class is a definition of a

This comprehensive text starts with a brief overview of the

user-defined typeC#(UDT)languagethat isandoftenthenregardedquickly movesas a blueprintto key technicalfor variablesand of this type. An object is simply a term describing aarchitecturgiven instancel issuesof aforparticular.NET developersclass. In. C#, the "new" keyword is the de facto way to create an object instance. Unlike other OO languages (such as C++), it is not possible to allocate a class type on the stack, and therefore if you attempt to use a class variable that has not been "new-ed" you are

Table of Contents

issued a compile time error. Thus the following illustrative C# logic is illegal:

C# and the .NET Platform, Second Edition

Introduction

// This is no good...

Part One - Introducing C# and the .NET Platform

Using System;

Chapter 1 - The Philosophy of .NET

class HelloClass

Chapter 2 - Building C# Applications

{

Part Two - The C# Programming Language

public static int Main(string[] args)

Chapter 3 - C# Language Fundamentals

{

Chapter 4 - Object-Oriented Programming with C#

// Error! Use of unassigned local variable! Must use 'new'.

Chapter 5 - ExcHelloClassptions and Objectc1; Lifetime

Chapter 6 - Interfacesc1.SayHi();and Collections

Chapter 7 - CallbackreturnInterfaces,0; Delegates, and Events

}

Chapter 8 - Advanced C# Type Construction Techniques

}

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

To illustrate the proper procedure for class instantiation, observe the following update:

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

// Make HelloClass typescorrectlyusing the C# 'new' keyword.

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Using System;

Chapter 14 - A Better Painting Framework (GDI+) class HelloClass

Chapter 15 - Programming with Windows Forms Controls

{

Chapter 16 - The System.IO Namespace

public static int Main(string[] args)

Chapter{17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

// You can declare and create a new object in a single line...

Chapter 18 - ASP.NET Web Pages and Web Controls

HelloClass c1 = new HelloClass();

Chapter 19 - ASP.NET Web Applications

// ...or break declaration and creation into two lines.

Chapter 20 - XML Web Services

HelloClass c2;

Index

c2 =

new HelloClass();

 

List of Figuresreturn 0;

List of Tables}

}

The "new" keyword is in charge of allocating the correct number of bytes for the specified class and acquiring sufficient memory from the managed heap. Here, you have allocated two objects (c1 and c2) each of which points to a unique instance of the HelloClass type. Understand that C# object variables are actually a reference to the object in memory, not the actual object itself. Thus, in this light, c1 and c2 each reference a distinct HelloClass object allocated on the managed heap (Chapter 4 offers additional details regarding the .NET garbage collector and the managed heap).

As you may be aware, the previous code is making calls to the default constructor of the class. Every C# class is automatically endowed with a default constructor, which you are free to redefine if need be. Like C++ (and Java), default constructors never take arguments. Beyond allocating a new class instance, the default constructor ensures that all member data is set to an appropriate default value (this behavior is true for all constructors). Contrast this to C++, where uninitialized state data points to garbage (sometimes the little things mean a lot).

This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.

Typically, your customC# andclassesthe .NETprovidePlatform,additionalSecondconstructorsEdition beyond the default. In doing so, you provide the object user withby Andrewa simpleTroelsenway to initialize the state of an objectISBN:1590590554at the time of creation. Here is the HelloClass type onceApr ssagain,© 2003with(1200apages)custom constructor, a redefined default constructor, and some simple state data:

// HelloClass, with constructors.

using System;

class HelloClass

Table of Contents

{

C# and the .NET Platform, Second Edition

// Constructors always assign state data to default values.

Introduction

public HelloClass()

Part One - Introducing C# and the .NET Platform

{ Console.WriteLine("Default ctor called!"); }

Chapter 1 - The Philosophy of .NET

// This custom constructor assigns state data to a known value.

Chapter 2 - Building C# Applications

public HelloClass (int x, int y)

Part Two{- The C# Programming Language

Chapter 3 - C# Language Fundamentals

Console.WriteLine("Custom ctor called!");

Chapter 4 - Object-Oriented Programming with C# intX = x;

Chapter 5 - Exceptions and Object Lifetime

intY = y;

Chapter }6 - Interfaces and Collections

Chapter //7 -SomeCallbackpublicInterfaces,stateDelegates,data.and Events

Chapter public8 - Advancedint C#intX,Type intY;Construction Techniques

Part Three - Programming with .NET Assemblies

// Program entry point.

Chapter 9 - Unde standing .NET Assemblies

public static int Main(string[] args)

Chapter 10 - Processes, AppDomains, Contexts, and Threads

{

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

// Trigger default constructor.

Part Four - Leveraging the .NET Libraries

HelloClass c1 = new HelloClass();

Chapter 12 - Object Serialization and the .NET Remoting Layer

Console.WriteLine("c1.intX = {0}\nc1.intY = {1}\n",

Chapter 13 - Building a Better Window (Introducing Windows Forms)

c1.intX, c1.intY);

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

// Trigger parameterized constructor.

Chapter 16 - The System.IO Namespace

HelloClass c2;

Chapter 17 - Data Access with ADO.NET

c2 = new HelloClass(100, 200);

Part Five - Web Applications and XML Web Services

Console.WriteLine("c2.intX = {0}\nc2.intY = {1}\n",

Chapter 18 - ASP.NET Web Pages and Web Controls

c2.intX, c2.intY);

Chapter 19 - ASP.NET Web Applications

return 0;

Chapter 20 - XML Web Services

}

Index

}

List of Figures

List of Tables

As you can see, C# constructors are named identical to the class they are constructing, and do not take a return value (not even void). On examining the program's output you can see that the default constructor has indeed assigned the internal state data to the default values (zero), while the custom constructor has assigned the member data to values specified by the object user (see Figure 3-3).

Chapter 20 - XML Web Services
Chapter 19 - ASP.NET Web Applications

Second Edition

ISBN:1590590554

with a brief overview of the

moves to key technical and

developers.

Table

C# and

Part One - Introducing C# and the .NET Platform

Figure 3-3: Simple constructor logic

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Is That a Memory Leak?

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

If you have a background in C++, you may be alarmed by the previous code samples. Specifically, notice

Chapter 5 - Exceptions and Object Lifetime

how the Main() method of the previous HelloClass type has no logic that explicitly destroys the c1 and c2

Chapter 6 - Interfaces and Collections variables:

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

// Leaky method?

Part Three - Programming with .NET Assemblies

public static int Main(string[] args)

Chapter 9 - Understanding .NET Assemblies

{

Chapter 10 - Processes, AppDomains, Contexts, and Threads

HelloClass c1 = new HelloClass();

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Console.WriteLine("c1.intX = {0}\nc1.intY = {1}\n", c1.intX, c1.intY);

Part Four - Leveraging the .NET Libraries

HelloClass c2;

Chapter 12 - Object Serialization and the .NET Remoting Layer c2 = new HelloClass(100, 200);

Chapter 13 - Building a Better WindowintX(In roducing Windows Forms)

Console.WriteLine("c2. = {0}\nc2.intY = {1}\n", c2.intX, c2.intY);

Chapter//14Hey!- A BetterDidPaintingsomeoneFrameworkforget(GDI+)to delete these objects?

Chapterreturn15 - Programming0; with Windows Forms Controls

Chapter} 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

This is not a horrible omission, but the way of .NET. Like Visual Basic and Java developers, C#

Chapter 18 - ASP.NET Web Pages and Web Controls

programmers never explicitly destroy an object. The .NET garbage collector frees the allocated memory automatically, and therefore C# does not support a "delete" keyword. Again, Chapter 4 examines the

garbage collection process in more detail. Until then, just remember that the .NET runtime environment

Index

automatically destroys the objects you allocate.

List of Figures

List of Tables

intX = x; intY = y;
Console.WriteLine("Custom ctor called!");

The CompositionC# and theof.NETa C#Platform,ApplicationSe ond Edition

by Andrew Troelsen

ISBN:1590590554

Currently, our HelloClass type has been constructed to perform two duties. First, the class defines the

Apress © 2003 (1200 pages)

entry point of the application. Second, HelloClass maintains two custom data members and a few

This comprehensive text starts with a brief overview of the

overloaded constructorsC# language. Whileandthisthenis allquicklywell andmovesgood,to keyit maytechnicalseemanda bit strange (although perfectly legal) that the staticar hitecturalMain() methodissuescreatesfor .NETandevelopersinstance. of the very class in which it was defined:

class HelloClass

Table of Contents

{

C# and the .NET Platform, Second Edition

...

Introduction

public static int Main(string[] args)

Part One - Introducing C# and the .NET Platform

{

Chapter 1 - The Philosophy of .NET

HelloClass c1 = new HelloClass();

Chapter 2 - Building C# Applications

...

Part Two - The C# Programming Language

}

Chapter 3 - C# Language Fundamentals

}

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Many of my initial examples take this approach, just to keep focused on illustrating the task at hand.

Chapter 6 - Interfaces and Collections

However, a more natural design would be to factor the HelloClass type into two distinct classes:

Chapter 7 - Callback Interfaces, Delegates, and Events

HelloClass and HelloApp. In OO parlance, this is termed the "separation of concerns." Thus, you could

Chapter 8 - Advanced C# Type Construction Techniques

reengineer the application as the following (notice you have added a new member named SayHi() to the

Part Three - Programming with .NET Assemblies

HelloClass type):

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

classHelloClass

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

{

Part Four - Leveraging the .NET Libraries

public HelloClass(){ Console.WriteLine("Default ctor called!"); }

Chapter 12 - Object Serialization and the .NET Remoting Layer

public HelloClass (int x, int y)

Chapter 13 - Building a Better Window (Introducing Windows Forms)

{

Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

}

Chapter 17 - Data Access with ADO.NET public int intX, intY;

Part Five - Web Applications and XML Web Services

public void SayHi() { Console.WriteLine("Hi there!"); }

Chapter 18 - ASP.NET Web Pages and Web Controls

}

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

classHelloApp

Index

{

List of Figurespublic static int Main(string[] args)

List of Tables{

// Make some HelloClass objects and say howdy.

HelloClass c1 = new HelloClass();

c1.SayHi();

...

}

}

When you build your C# applications, it becomes quite common to have one type functioning as the "application object" (the type that defines the Main() entry point) and numerous other types that constitute the application at large. On the other hand, it is permissible to create an application object that defines any number of members called from the type's Main() method. You will see examples of each approach during the remainder of this text.

Note If you are coming to .NET from an MFC background, be aware that there is no intrinsic doc / view / frame / app model under .NET. If you desire such a paradigm, you must roll your own.

SOURCE

CODE

C# andThe theHelloThere.NET Platform,project isSecondlocatedEditionunder the Chapter 3 subdirectory.

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.

Table of Contents

C# and the .NET Platform, Second Edition

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Default AssignmentsC# a d the .NETandPlatform,VariableSecond EditiScopen

by Andrew Troelsen

ISBN:1590590554

As seen in the previous example, all intrinsic .NET data types have a default value. When you create custom

Apress © 2003 (1200 pages)

types, all member variables are automatically assigned to their appropriate default value. To illustrate, assume

This comprehensive text starts with a brief overview of the

you have createdC#a newlanguageConsoleand applicationthen quicklycontainingmoves to keythe technicalfollowingandclass type:

architectural issues for .NET developers.

// C# automatically sets all member variables to a safe default value.

class DefaultValueTester

Table of Contents

{

C# and the .NET Platform, Second Edition

// Here are a number of fields...

Introduction

public sbyte theSignedByte;

Part One - Introducing C# and the .NET Platform

public byte theByte;

Chapter 1 - The Philosophy of .NET

public short theShort;

Chapter 2 - Building C# Applications

public ushort theUShort;

Part Two - The C# Programming Language

public int theInt;

Chapter 3 - C# Language Fundamentals

public uint theUInt;

Chapter 4 - Object-OrientheLong;ed Programming with C# public long

Chapter public5 - Ex eptionsulongandtheULong;Object Lifetime

Chapter public6 - InterfacescharandtheChar;Collections

Chapter public7 - CallbackfloatIn erfactheFloat;s, Delegates, and Events

public double theDouble;

Chapter 8 - Advanced C# Type C nstruction Techniques

public bool theBool;

Part Three - Programming with .NET Assemblies

public decimal theDecimal;

Chapter 9 - Understanding .NET Assemblies

public string theStr;

Chapter 10 - Processes, AppDomains, Contexts, and Threads

public object theObj;

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

public static int Main(string[] args)

Part Four - Leveraging the .NET Libraries

{

Chapter 12 - Object Serialization and the .NET Remoting Layer

DefaultValueTester v = new DefaultValueTester();

Chapter 13 - Building a Better Window (Introducing Windows Forms)

return 0; // Set breakpoint here and check out the Locals windo

Chapter 14 - A Better Painting Framework (GDI+)

}

Chapter 15 - Programming with Windows Forms Controls

}

Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET

PartIf youFivewere- Webto nowApplicationscreate anandinstanceXML Webof theServicesDefaultValueTester class and begin a debugging session, you wou

Chaptersee that18each- ASPmember.NET WebvariableP ges andhas WbeenConautomaticallyrols assigned to a corresponding default value, as seen in

ChapterFigure 193-4-. ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of

List of

Figure 3-4: Viewing default values for member data

The story is very different, however, when you create variables within a method scope. When you define variabl within a method scope, you must assign an initial value before you use them, as they do not receive a default assignment. For example, the following code results in a compiler error:

C# and the .NET Platform, Second Edition

// Compiler error! Must assign localInt to an initial value before use.

by Andrew Troelsen

ISBN:1590590554

public static void Main()

 

{Apress © 2003 (1200 pages)

int localInt;This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

Console.WriteLine(localInt);

architectural issues for .NET developers.

}

Table of Contents

Fixing the problem is trivial. Simply make an initial assignment:

C# and the .NET Platform, Second Edition

Introduction

// Better. Everyone is happy.

Part One - Introducing C# and the .NET Platform

public static void Main()

Chapter 1 - The Philosophy of .NET

{

Chapter 2 - Building C# Applications

int localInt = 0;

Part Two - The C# Programming Language

Console.WriteLine(localInt);

Chapter 3 - C# Language Fundamentals

}

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

There is one exception to the mandatory assignment of local variables. If the variable is functioning as an "outp

Chapter 7 - Callback Interfaces, Delegates, and Events

parameter (examined a bit later in this chapter) the variable does not need to be assigned an initial value. The

Chapter 8 - Advanced C# Type Construction Techniques

rationale for this is simple: Methods that define output parameters assign incoming variables within their functio

Part Three - Programming with .NET Assemblies

scope before the caller makes direct use of them.

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

SOURCE The DefaultValues project is located under the Chapter 3 subdirectory.

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

CODE

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

The C# MemberC# and Variablethe .NET Platform,InitializationSecond EditionSyntax

by Andrew Troelsen

ISBN:1590590554

Class types tend to have numerous member variables. Given that a class may define various custom

Apress © 2003 (1200 pages)

constructors, you can find yourself in the annoying position of having to write the same initialization code in

This comprehensive text starts with a brief overview of the

each and every constructorC# languageimplementationand then quickly. Thismovesis particularlyto key technecessaryical and if you do not wish to accept the default values assignedarchitecturalto yourissuesstatefordata.NET. Fordevelopersexample,. if you wish to ensure that an integer member variable always begins life with the value of 9, you could write:

Table of Contents

// This is OK, but redundant...

C# and the .NET Platform, Second Edition

class Test

Introduction

{

Part One - Introducing C# and the .NET Platform

private int myInt;

Chapter 1 - The Philosophy of .NET

Test() { myInt = 9; }

Chapter 2 - Building C# Applications

Test(string someStringParam)

Part Two - The C# Programming Language

{ myInt = 9; }

Chapter 3 - C# Language Fundamentals

Test(bool someBoolParam)

Chapter 4 - Object-Oriented Programming with C#

{ myInt = 9; }

Chapter...5 - Exceptions and Object Lifetime

Chapter} 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

An alternative would be to define a private helper function for your class type that is called by each

Part Three - Programming with .NET Assemblies

constructor. While this will reduce the amount of repeat assignment code, you are now stuck with the

Chapter 9 - Understanding .NET Assemblies

following redundancy:

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

// This is still rather redundant...

Part Four - Leveraging the .NET Libraries

class Test

Chapter 12 - Object Serialization and the .NET Remoting Layer

{

Chapter 13 - Building a Better Window (Introducing Windows Forms)

private int myInt;

Chapter 14 - A Better Painting Framework (GDI+)

Test() { InitData(); }

Chapter 15 - Programming with Windows Forms Controls

Test(string someStringParam)

Chapter 16 - The System.IO Namespace

{ InitData(); }

Chapter 17 - Data Access with ADO.NET

Test(bool someBoolParam)

Part Five - Web Applications and XML Web Services

{ InitData(); }

Chapter 18 - ASP.NET Web Pages and Web Controls

private void InitData()

Chapter 19 - ASP.NET Web Applications

{ myInt = 9; }

Chapter 20 - XML Web Services

...

Index

}

List of Figures

List of Tables

While both of these techniques are still valid, C# allows you to assign a type's member data to an initial value at the time of declaration [as you may be aware, other object-oriented languages (such as C++) do not allow you to initialize a member in this way]. Notice in the following code blurb that member initialization may be used with internal object references as well as numerical data types:

//This technique is useful when you don't want to accept default values

//and would rather not write the same initialization code in each constructor.

class Test

{

private int myInt = 9;

private string myStr = "My initial value.";

private HotRod viper = new HotRod(200, "Chucky", Color.Red);

...

}

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Note Be aware that member assignment happens before constructor logic. Thus, if you assign a

Apress © 2003 (1200 pages)

member to a value within the scope of a constructor, it effectively cancels out the previous member

This comprehensive text starts with a brief overview of the assignment.

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

In addition to each of these member variable initialization techniques, yet another option is to forward calls from one constructor to another "master" constructor. You will see this technique later in Chapter 4 during

our discussion of the "this" keyword.

Table of Contents

C# and the .NET Platform, Second Edition

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Basic InputC#andand theOutput.NET Platform,with theSecondConsoleEditi n Class

by Andrew Troelsen

ISBN:1590590554

Many of the example applications seen over the course of these first few chapters make use of the

Apress © 2003 (1200 pages)

System.Console class. Console is one of many types defined in the System namespace. As its name

This comprehensive text starts with a brief overview of the

implies, this classC#encapsulateslanguage andinput,thenoutput,quickly andmoverrors to keystreamtechnicalmanipulationsand . Thus, you are correct to assume that this architecturaltype is mostlyissuesusefulforwhen.NETcreatingdevelopersconsole. -based applications rather than Windowsbased or Web-based applications.

TablePrincipalof Contentsamong the methods of System.Console are Read(), ReadLine() Write() and WriteLine(), all of C#whichand arethe .definedNET Platform,as staticSecond. As youEditionhave seen, WriteLine() pumps a text string (including a carriage return)

to the output stream. The Write() method pumps text to the output stream without a carriage return.

Introduction

ReadLine() allows you to receive information from the input stream up until the carriage return, while

Part One - Introducing C# and the .NET Platform

Read() is used to capture a single character from the input stream.

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

To illustrate basic IO using the Console class, consider the following program, which prompts the user for

Part Two - The C# Programming Language

some bits of information and echoes each item to the standard output stream. The output can be seen in

Chapter 3 - C# Language Fundamentals

Figure 3-5.

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Based Programming

Part

Figure 3-5: Basic IO using System.Console

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

// Make use of the Console class to perform basic IO.

Chapter 15 - Programming with Windows Forms Controls

using System;

Chapter 16 - The System.IO Namespace

class BasicIO

Chapter 17 - Data Access with ADO.NET

{

Part Five - Web Applications and XML Web Services

public static void Main(string[] args)

Chapter 18 - ASP.NET Web Pages and Web Controls

{

Chapter 19 - ASP.NET Web Applications

// Echo some stats.

Chapter 20 - XML Web Services

Console.Write("Enter your name: ");

Index

string s;

List of Figures

s = Console.ReadLine();

List of TablesConsole.WriteLine("Hello, {0} ", s); Console.Write("Enter your age: ");

s = Console.ReadLine(); Console.WriteLine("You are {0} years old", s);

}

}

Formatting Textual Output

During these first few chapters, you have also seen numerous occurrences of the tokens {0}, {1}, and the like. .NET introduces a new style of string formatting, slightly reminiscent of the C printf() function, without the cryptic "%d" "%s'" or "%c" flags. A simple example follows (see the output in Figure 3-6).

Second Edition

ISBN:1590590554

with a brief overview of the

moves to key technical and

developers.

Table

C# and

Figure 3-6: Simple format characters

Part One - Introducing C# and the .NET Platform

Chapter

1

- The Philosophy of .NET

 

 

 

Chapter

2

- Building C# Applications

 

 

 

PartusingTwo -System;The C# Programming Language

 

 

 

Chapterclass3BasicIO- C# Language Fundamentals

 

 

 

Chapter{

4

- Object-Oriented Programming with C#

args)

 

 

Chapter public5 - ExceptionsstaticandvoidObjectMain(string[]Lifetime

 

 

Chapter {6

- Interfaces and Collections

 

 

 

Chapter

7

...

 

 

 

- Callback Interfaces, Delegates, and Events

 

 

 

Chapter

8

int theInt = 90;

 

 

 

- Advanced C# Type Construction Techniques

 

 

 

 

float theFloat = 9.99;

 

 

 

Part Three - Programming with .NET Assemblies

 

 

 

Chapter

9

BasicIO myIO = new BasicIO();

 

 

- Understanding .NET Assemblies

 

 

 

 

 

// Format a string...

 

 

 

Chapter

10

- Processes, AppDomains, Contexts, and Threads

{1}\nYou Are:

{2}",

 

 

Console.WriteLine("Int is:

{0}\nFloat is:

Chapter

11

- Type Reflection, Late Binding, and Attribute-Based Programming

 

 

 

 

theInt, theFloat, myIO.ToString());

 

Part Four - Leveraging the .NET Libraries

}

Chapter 12 - Object Serialization and the .NET Remoting Layer

}

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

The first parameter to WriteLine() represents a format string that contains optional placeholders

Chapter 16 - The System.IO Namespace

designated by {0}, {1}, {2}, and so forth. The remaining parameters to WriteLine() are simply the values to

Chapter 17 - Data Access with ADO.NET

be inserted into the respective placeholders (in this case, an integer, a float, and a string). Also be aware

Part Five - Web Applications and XML Web Services

that WriteLine() has been over-loaded to allow you to specify placeholder values as an array of objects.

Chapter 18 - ASP.NET Web Pages and Web Controls

Thus, you can represent any number of items to be plugged into the format string as follows:

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

// Fill placeholders using an array of objects.

Index

object[] stuff = {"Hello", 20.9, 1, "There", "83", 99.99933} ;

List of Figures

Console.WriteLine("The Stuff: {0} , {1} , {2} , {3} , {4} , {5} ", stuff);

List of Tables

It is also permissible for a given placeholder to repeat within a given string. For example, if you want to build the string "9Number9Number9" you would write:

// John says...

Console.WriteLine("{0}Number{0}Number{0}", 9);

Note If you have a mismatch between the number of curly-bracket placeholders and fill-arguments, you will receive a FormatException exception at runtime.

String Formatting Flags

If you require more elaborate formatting, each placeholder can optionally contain various format

characters (in either uppercase or lowercase), as seen in Table 3-1.

C# and the .NET Platform, Second Edition

 

 

 

by Andrew Troelsen

ISBN:1590590554

 

Table 3-1: .NET String Format Characters

 

 

 

 

C# Format

Apress © 2003 (1200 pages)

 

 

 

 

This Meaningcomprehensivein Lifetext starts with a brief overview of the

 

 

 

Character C# language and then quickly moves to key technical and

 

 

 

 

 

architectural issues for .NET developers.

 

 

 

 

C or c

 

 

Used to format currency. By default, the flag will prefix the local cultural

 

 

 

 

 

 

symbol [a dollar sign ($) for US English], however, this can be changed using

 

Table of Contents

 

 

a System.Globalization.NumberFormatInfo object.

 

 

 

 

 

 

C# and the .NET Platform, Second Edition

 

 

 

 

D or d

 

 

Used to format decimal numbers. This flag may also specify the minimum

 

Introduction

 

 

number of digits used to pad the value.

 

 

 

 

 

 

 

 

 

Part One - Introducing

 

C# and the .NET Platform

 

 

 

 

 

ChapterE or e1 - The PhilosophyExponentialof .NETnotation.

 

 

 

 

 

 

 

 

 

Chapter 2 - Building

 

C# Applications

 

 

 

 

F or f

 

 

Fixed point formatting.

 

 

Part Two - The C#

Programming Language

 

 

 

 

ChapterG or g3 - C# LanguageStandsFundamentalsfor general. Used to format a number to fixed or exponential format.

 

 

 

 

 

 

 

 

Chapter 4 - Object-

 

Oriented Programming with C#

 

 

 

 

N or n

 

 

Basic numerical formatting (with commas).

 

 

 

Chapter 5 - Exceptions

 

and Object Lifetime

 

 

 

 

 

 

 

 

ChapterX or x6 - Interfaces

 

Hexadecimaland Collectionsformatting. If you use an uppercase X, your hex format will also

 

 

Chapter 7 - Callback

 

Interfaces,contain uppercaseDelegates,characters.and Events

 

 

 

 

 

 

 

 

 

 

Chapter 8 - Advanced C# Type Construction Techniques

 

 

Part Three - Programming with .NET Assemblies

These format characters are suffixed to a given placeholder using the colon token (for example, {0:C},

Chapter 9 - Understanding .NET Assemblies

{1:d}, {2:X}, and so on). To illustrate, assume you have updated Main() with the following logic:

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

// Now make use of some format tags.

Part Four - Leveraging the .NET Libraries

public static void Main(string[] args)

Chapter 12 - Object Serialization and the .NET Remoting Layer

{

Chapter 13 - Building a Better Window (Introducing Windows Forms)

...

Chapter 14 - A Better Painting Framework (GDI+)

Console.WriteLine("C format: {0:C}", 99989.987);

Chapter 15 - Programming with Windows Forms Controls

Console.WriteLine("D9 format: {0:D9}", 99999);

Chapter 16 - The System.IO Namespace

Console.WriteLine("E format: {0:E}", 99999.76543);

Chapter 17

- Data Access with ADO.NET

 

Console.WriteLine("F3 format: {0:F3}", 99999.9999);

Part Five - Web Applications and XML Web Services

Console.WriteLine("N format:

{0:N}", 99999);

Chapter 18

- ASP.NET Web Pages and Web Controls

Console.WriteLine("X format:

{0:X}", 99999);

Chapter 19

- ASP.NET Web Applications

{0:x}", 99999);

Console.WriteLine("x format:

Chapter} 20 - XML Web Services

Index

List of Figures

Be aware that the use of the C# formatting characters is not limited to the System.Console.WriteLine()

List of Tables

method. For example, these same flags can be used within the context of the static String.Format() method. This can be helpful when you need to build a string containing numerical values in memory and display it at a later time:

// Use the static String.Format() method to build a new string.

string formStr;

formStr =

String.Format("Don't you wish you had {0:C} in your account?",

99989.987);

Console.WriteLine(formStr);

Figure 3-7 shows a test run.

Second Edition

ISBN:1590590554

a brief overview of the

moves to key technical and

developers.

Figure 3-7: String format flags in action

Table of Contents

C# andSOURCEthe .N T Platform,TheSecondBasicIOEditionproject is located under the Chapter 3 subdirectory.

IntroductionCODE

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

UnderstandingC# andValuethe .NETTypesPlatform,andSecondReferenceEdition Types

by Andrew Troelsen

ISBN:1590590554

Like any programming language, C# defines a number of intrinsic (aka "primitive") keywords that represent

Apress © 2003 (1200 pages)

basic data types. As you would expect, there are types to represent whole numbers, strings, floating-point

This comprehensive text starts with a brief overview of the

numbers, and BooleanC# languagevaluesand. If youthenarequicklycomingmovesfromtoakeyC++technicalbackground,and you will be happy to know that these intrinsic typesarchitarecturalfixed issuesconstantsfor .inNETthedevelopersuniverse..Meaning, when you create a data point of type integer, all.NET-aware languages understand the fixed nature of this type, and all agree on the range it is capable of handling.

Table of Contents

C#Specificallyand the .NETspeaking,Platform,a .SecondNET dataEditiontype may be value-based or reference-based. Value-based types, which

include all numerical data types (int, float, etc.) as well as enumerations and structures, are allocated on the

Introduction

stack. Given this factoid, value types can be quickly removed from memory once they fall out of the defining

Part One - Introducing C# and the .NET Platform

scope:

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part// TwoIntegers- The C#areP ogrammingvalue types!Language

Chapterpublic3 void- C# LanguageSomeMethod()Fun amentals

{

Chapter 4 - Object-Oriented Programming with C#

int i = 0;

Chapter 5 - Exceptions and Object Lifetime

Console.WriteLine(i);

Chapter 6 - Interfaces and Collections

} // 'i' is popped off the stack here!

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

When you assign one value type to another, a member-by-member copy is achieved by default. In terms of

Chapter 9 - Understanding .NET Assemblies

simple data types (such as integers and floats), the only "member" to copy is the value of the variable itself.

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

// Assigning two intrinsic value types results in

Part Four - Leveraging the .NET Libraries

// two independent variables on the stack.

Chapter 12 - Object Serialization and the .NET Remoting Layer public void SomeMethod()

Chapter 13 - Building a Better Window (Introducing Windows Forms)

{

Chapter 14 - A Better Painting Framework (GDI+) int i = 99;

Chapter 15 - Programming with Windows Forms Controls int j = i;

Chapter 16 - The System.IO Namespace

// After the following assignment, i is still 99.

Chapter 17 - Data Access with ADO.NET j = 8732;

Part} Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

While the previous example is no major news flash, recall that custom .NET structures and enumerations

Chapter 20 - XML Web Services

also fall under the value-type category. To illustrate, assume you have the following C# structure (you

Index

examine structures in greater detail later in this chapter):

List of Figures

List of Tables

// Structures are value types!

struct FOO

{

public int x, y;

}

Now, observe the following Main() logic (the output can be seen in Figure 3-8).

ISBN:1590590554

overview of the technical and

Table

C# and

Part

Chapter 1 - The Philosophy of .NET

Figure 3-8: Assignment of value types results in a verbatim copy of each field.

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

class ValRefClass

Chapter{ 4 - Object-Oriented Programming with C#

Chapter //5 -ExerciseExcept ons andsomeObjectvaluLifetimetypes.

Chapter public6 - Interfacesstaticand intCollectionsMain(string[] args)

{

Chapter 7 - Callback Interfaces, Delegates, and Events

// The 'new' keyword is optional when creating structures

Chapter 8 - Advanced C# Type Construction Techniques

// using the default constructor, however you must assign

Part Three - Programming with .NET Assemblies

Chapter 9

- Understanding// all field.NET Assembliesdata before use.

Chapter 10

- Processes,FOO f1 AppDomains,= new FOO();Contexts, and Threads

Chapter 11

- Typef1.xReflection,= 100;Late Binding, and Attribute-Based Programming

Part Four -

 

f1.y = 100;

 

Leveraging the .NET Libraries

Chapter 12

- ObjectConsole.WriteLine("Serialization and the .NET-> RemotingAssigningLayerf2 to f1\n");

Chapter 13

 

FOO f2 = f1;

- Building a Better Window (Introducing Windows Forms)

Chapter 14

 

// Here is F1.

- A Better Painting Framework (GDI+)

Chapter 15

 

Console.WriteLine("F1.x = {0}", f1.x);

- Programming with Windows Forms Controls

 

 

Console.WriteLine("F1.y = {0}", f1.y);

Chapter 16

- The System.IO Namespace

 

 

// Here is F2.

Chapter 17

- Data Access with ADO.NET

 

 

Console.WriteLine("F2.x = {0}", f2.x);

Part Five - Web Applications and XML Web Services

 

 

Console.WriteLine("F2.y = {0}", f2.y);

Chapter 18

- ASP.NET Web Pages and Web Controls

 

 

// Change f2.x. This will NOT change f1.x.

Chapter 19

- ASP.NET Web Applicatio s

 

 

Console.WriteLine("-> Changing f2.x to 900");

Chapter 20

- XML Web Services

 

 

f2.x = 900;

Index

 

// Print again.

List of Figures

Console.WriteLine("-> Here are the X's again...");

List of Tables

Console.WriteLine("F2.x = {0}", f2.x);

 

 

Console.WriteLine("F1.x = {0}\n", f1.x);

}

 

return 0;

 

 

}

 

 

Here you have created a structure of type FOO (named f1) that is then assigned to another FOO structure (f2). Because FOO is a value type, you have two copies of the FOO type on the stack, each of which can be independently manipulated. Therefore, when you change the value of f2.x, the value of f1.x is unaffected (just like the behavior seen in the previous integer example).

In stark contrast, reference types (classes) are allocated on the garbage-collected heap. These entities stay in memory until the .NET garbage collector destroys them. By default, assignment of reference types results in a new reference to the same object in memory. To illustrate, let's change the definition of the FOO type from a C# structure to a C# class:

 

C# and the .NET Platform, Second Edition

 

// Classes are always reference types.

ISBN:1590590554

class

by Andrew Troelsen

FOO // <= Now a class!

 

{

Apress © 2003 (1200 pages)

 

This comprehensive text starts with a brief overview of the

 

public int x, y;

 

}

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

 

If you were to run our test program once again, you would notice the change in behavior (Figure 3-9). Here,

Table of Contents

you have two references pointing to the same object on the managed heap. Therefore, when you change

C# and the .NET Platform, Second Edition

the value of x using the f2 reference, f1.x reflects the same value.

Introduction

Part One - Introducing C# and the .NET Platform

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

 

Chapter

 

Chapter

Programming

Figure 3-9: Assignment of reference types copies the reference.

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Value Types Containing Reference Types

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Now that you have a better feeling for the core differences between value types and reference types, let's

Chapter 16 - The System.IO Namespace

see a more complex example. Assume you have the following reference (class) type:

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

class TheRefType

Chapter 18 - ASP.NET Web Pages and Web Controls

{

Chapter 19 - ASP.NET Web Applications public string x;

Chapter 20 - XML Web Services

public TheRefType(string s) {x = s;}

Index

}

List of Figures

List of Tables

Now assume that you want to contain a variable of this reference type within a value type (structure) named InnerRef. In addition to this internal reference type, also assume that InnerRef defines a simple integer (value type) data member. Finally, to allow the outside world to set the value of the inner TheRefType, we also provide the following custom constructor (as explained in just a bit, the default constructor of a structure is reserved and cannot be redefined):

struct InnerRef

 

{

// Reference type.

public TheRefType refType;

public int structData;

// Value type.

public InnerRef(string s)

 

{

 

refType = new TheRefType(s);

 

structData = 9;

 

}

 

}

C# and the .NET Platform, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

At this point, you Aprhavesscontained© 2003 (1200a pagreferences) type within a value type. The million-dollar question would now be: what happensThisif youcomprehensiveassign one InnerReftext startsvariablew th a briefto another?overviewGivenof thewhat you already know about value types, you wouldC#be correctlanguageinandassumingthen quicklythat themovesstructDatato key technicalinteger shouldand be an independent entity for

architectural issues for .NET developers.

each InnerRef variable (as a copy was achieved). But what about the internal reference type? Will the object's state be fully copied, or will the reference to that object be copied? Ponder the following code and

check out Figure 3-10 for the answer.

Table of Contents

C# and the .NET Platform, Second Edition

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter 5 - Exceptions and Object Lifetime

Figure 3-10: The internal references point to the same object!

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

// Make value type that contains ref type.

PartConsoleThree -.ProgrammingWriteLine("with-> .NETMakingAssembliesInnerRef type and setting structData to 666");

ChaptInnerRef9 - UnderstandingvalWithRef.NET= newAssembliesInnerRef("Initial value");

ChvalWithRefpter 10 - Processes,.structDataAppDomains,= 666;Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part// FourNow- assignLeveraginga thenew.NETInnerRefLibrari s

Console.WriteLine("-> Assigning valWithRef2 to valWithRef");

Chapter 12 - Object Serialization and the .NET Remot ng Layer

InnerRef valWithRef2;

Chapter 13 - Building a Better Window (Introducing Windows Forms)

valWithRef2 = valWithRef;

Chapter 14 - A Better Painting Framework (GDI+)

// Change the value of the internal reference type.

Chapter 15 - Programming with Windows Forms Controls

Console.WriteLine("-> Changing all values of valWithRef2");

Chapter 16 - The System.IO Namespace

valWithRef2.refType.x = "I am NEW!";

Chapter 17 - Data Access with ADO.NET

valWithRef2.structData = 777;

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

// Print everything.

Chapter 19 - ASP.NET Web Applications

Console.WriteLine("-> Values after change:");

Chapter 20 - XML Web Services

Console.WriteLine("-> valWithRef.refType.x is {0}", valWithRef.refType.x);

Index

Console.WriteLine("-> valWithRef2.refType.x is {0}", valWithRef2.refType.x);

List of Figures

Console.WriteLine("-> valWithRef.structData is {0}", valWithRef.structData);

List of Tables

Console.WriteLine("-> valWithRef2.structData is {0}", valWithRef2.structData);

As you can see, the state of the internal reference type (refType) was not fully copied into the new InnerRef variable. By default, when a value type contains other reference types, assignment results in a copy of the references. In this way, you have two independent structures, each of which contains a reference pointing to the same object in memory (i.e., a "shallow copy"). When you want to perform a "deep copy," where the state of internal references is fully copied into a new object, you need to implement the ICloneable interface (as you do in Chapter 6).

Value and Reference Types: Final Details

To wrap up our examination of value types and reference types, ponder the information in Table 3-2 that illustrates how each stands up against a number of intriguing questions (many of which are examined in greater detail throughout this text).

Table 3-2: Value Types and Reference Types Side by Side

C# and the .NET Platform, Second Edition

Intriguing

by Andrew TroelsenValue Type

ISBN:1590590554Reference Type

Question

Apress © 2003 (1200 pages)

 

 

 

 

 

 

 

 

 

 

 

This comprehensive text starts with a brief overview

of the

Where is this type

 

Allocated on the stack.

 

 

Allocated on the managed heap.

allocated?

C# language and then quickly moves to key technical and

architectural

 

issues for .NET developers.

 

 

 

 

 

How is a variable

 

Value type variables are local

 

 

 

represented?

 

copies.

 

Table of Contents

 

 

 

C# and the .NET Platform, Second Edition

 

 

 

IntroductionWhat is the base type?

 

Must directly derive from

 

Part One - Introducing C# andSystemthe .NET.ValueTypePlatform .

 

Chapter 1 - The Philosophy of .NET

 

 

Chapter 2 - Building C# Applications

 

 

 

 

 

 

 

Part Two - The C# Programming

Language

 

 

 

Can this type function

 

No. Value types are always

 

Chapter 3 - C# Language

Fundamentals

 

 

 

as a base to other

 

sealed and cannot be extended.

 

Chapter 4 - Object-Oriented

Programming with C#

 

 

 

types?

 

 

 

 

Chapter 5 - Exceptions and

 

Object Lifetime

 

 

 

Default parameter

 

Variables are passed by value

Chapter 6 - Interfaces and Collections

 

 

passing behavior?

 

(i.e., a copy of the variable is

Chapter 7 - Callback Interfaces, Delegates, and Events

passed into the called function).

Chapter 8 - Advanced C# Type Construction Techniques

PartAbleThreeto override- Programming withNo.NET. ValueAssembliestypes are never placed

ChapterObject9.Finalize()?- Und rstanding .NETontoAssthembliesheap and therefore do

Chapter 10 - Processes, AppDomains,not needContexts,to be finalizednd Threads.

Reference type variables are pointing to the memory occupied by the allocated instance.

Can derive from any other type (except System.ValueType) as long as that type is not "sealed"...

more later.

Yes. If the type is not sealed, it may function as a base to other types.

Variables are passed by reference (e.g., the address of the variable is passed into the called function).

Yes...indirectly (more details in Chapter 4).

 

 

 

 

 

 

 

 

 

 

 

Chapter 11 - Type Reflection,

 

Late Binding, and Attribute-Based Programming

 

Can I define

 

 

Yes, but the default constructor is

But, of course!

Part Four - Leveraging the .NET Libraries

 

 

constructors for this

 

 

reserved (i.e., your custom

 

Chapter 12 - Object Serialization and the .NET Remoting Layer

 

 

type?

 

 

 

constructors must all have

 

Chapter 13

- Building a Better Window (Introducing Windows Forms)

 

 

 

 

 

 

arguments).

 

 

Chapter 14

- A Better Painting

 

Framework (GDI+)

 

 

 

 

 

 

 

 

 

ChapterWhen15do-variablesProgrammingof

withWhenWindowsit fallsFormsout ofControlsthe defining

 

 

 

When the managed heap is

 

this type die?

 

 

scope.

 

 

 

garbage collected.

 

Chapter 16

- The System.IO

 

Namespace

 

 

 

 

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Despite their differences, value types and reference types both have the ability to implement interfaces, and

Chapter 18 - ASP.NET Web Pages and Web Controls

may support any number of fields, methods, overloaded operators, constants, properties, and events.

Chapter 19 - ASP.NET Web Applications

ChapterSOURCE20 - XML WebTheServicesValAndRef project is located under the Chapter 3 subdirectory.

IndexCODE

List of Figures

List of Tables

public Type GetType();
public virtual Int32 GetHashCode();
public virtual Boolean Equals(Object obj);

The MasterC#Node:and theSystem.NET Platform,.ObjectS ond Edition

by Andrew Troelsen

ISBN:1590590554

In C#, every data type (value or reference based) is ultimately derived from a common base class:

Apress © 2003 (1200 pages)

System.Object. The Object class defines a common polymorphic behavior for every type in the .NET

This comprehensive text starts with a brief overview of the

universe. In the previousC# languageHelloClassand thentypequicklydefinition,m vesyouto keydid nottechnicalexplicitlyandindicate that Object was the base class, but this is assumedarchitecturalif youissuesdo notf r say.NETotherwise:develop rs.

// Implicitly deriving from System.Object.

Table of Contents

class HelloClass {...}

C# and the .NET Platform, Second Edition

Introduction

PartIf youOnewish- Introducto explicitlyng C#stateandSystemthe .NET.ObjectPlatformas your base class, you are free to define your class definitions

Chapterusing either1 - Theof thePhilfollowings phy ofnotations:.NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

// Here we are explicitly deriving from System.Object.

Chapter 3 - C# Language Fundamentals

class HelloClass : System.Object {...}

Chapter 4 - Object-Oriented Programming with C#

// Same story here...

Chapter 5

- Exceptions and Ob

Lifetime

class

HelloClass : object {...}

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Like most .NET classes, System.Object defines a set of instance-level and class-level (static) members.

Chapter 8 - Advanced C# Type Construction Techniques

Note that some of these items are declared "virtual," and can therefore be overridden by a derived class:

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

// The topmost class in the .NET world: System.Object

Chapter 10 - Processes, AppDomains, Contexts, and Threads

namespaceSystem

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

{

Part Four - Leveraging the .NET Libraries

public class Object

Chapter 12 - Object Serialization and the .NET Remoting Layer

{

Chapter 13 - Building a Better Window (Introducing Windows Forms)

public Object();

Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

public virtual String ToString();

Part Five - Web Applications and XML Web Services

protected virtual void Finalize();

Chapter 18 - ASP.NET Web Pages and Web Controls protected Object MemberwiseClone();

Chapter 19 - ASP.NET Web Applications

public static bool Equals(object objA, object objB);

Chapter 20 - XML Web Services

public static bool ReferenceEquals(object objA, object objB);

Index }

List of Figures

}

List of Tables

Table 3-3 offers a rundown of the functionality provided by each instance-level method.

Table 3-3: Core Members of System.Object

 

 

 

 

 

 

 

 

 

 

Instance MethodC# and theMeaning.NET Platform,in LifeSecond Edition

 

 

 

of Object Classby Andrew Troelsen

ISBN:1590590554

 

 

 

 

 

 

 

 

 

 

 

Equals()

Apress © 2003 (1200 pages)

 

 

 

 

 

 

By default this method returns true only if the items being compared

 

 

 

 

This comprehensive text starts with a brief overview of the

 

 

 

 

 

 

refer to the exact same item in memory. Thus, Equals() is used to

 

 

 

 

C# language and then quickly moves to key technical and

 

 

 

 

architecturalcompareissues forobject.NET developers.references, not the state of the object.

 

 

 

 

 

 

Typically, this method is overridden to return "true" only if the objects

 

Table of Contents

 

being compared have the same internal state values (that is, value-

 

 

based semantics). Be aware that if you override Equals(), you should

 

C# and the .NET Platform, Second Edition

 

 

 

 

 

 

 

also override GetHashCode().

 

 

 

 

 

 

 

 

 

Introduction

 

Returns an integer that identifies a specific object instance. If you

 

 

 

GetHashCode()

 

 

Part One - Introducing C# and the .NET Platform

 

Chapter 1

 

 

intend your custom types to be contained in a

 

- The Philosophy of .NET

 

 

Chapter 2

 

 

System.Collections.Hashtable type, you are well advised to override

 

- Building C# Applications

 

 

 

 

 

 

 

the default implementation of this member.

 

Part Two - The C# Programming

Language

 

 

 

Chapter 3 - C# Language

 

Fundamentals

 

 

 

 

GetType()

 

This method returns a System.Type object that fully describes details

 

 

Chapter 4 - Object-Oriented

 

Programmingof the type youwithareC#currently referencing. In short, this is a Runtime

 

 

Chapter 5 - Exceptions and

 

ObjectType LifetimeIdentification (RTTI) method available to all objects (discussed in

 

 

Chapter 6 - Interfaces and

 

Collectionsgreater detail in Chapter 11).

 

 

 

 

 

 

 

 

Chapter 7 - Callback Interfaces, Delegates, and Events

 

 

 

ToString()

 

Returns a string representation of a given object, using the

 

 

Chapter 8

- Advanced C# Type Construction Techniques

 

 

 

 

 

 

"<namespace.<class name." format (termed the "fully qualified

 

Part Three - Programming with .NET Assemblies

 

 

 

 

 

 

name"). If the type has not been defined within a namespace, <class

 

Chapter 9 - Understanding .NET Assemblies

 

 

 

 

 

 

 

name. alone is returned. This method can be overridden by a subclass

 

Chapter 10 - Processes, AppDomains, Contexts, and Threads

 

 

 

 

 

 

to return a tokenized string of name/value pairs that represent the

 

Chapter 11 - Type Reflection, Late Bindi g, and Attribute-Based Programming

 

 

 

 

 

 

object's internal

state, rather than its fully qualified name.

 

 

 

 

 

 

 

Part Four - Leveraging the .NET Libraries

 

 

 

 

Finalize()

 

For the time being, you can understand this protected method (when

 

Chapter 12 - Object Serialization and the .NET Remoting Layer

 

 

 

 

 

 

overridden) is invoked by the .NET runtime when an object is to be

 

Chapter 13 - Building a Better Window (Introducing Windows Forms)

 

 

 

 

 

 

removed from the heap. We talk more about the CLR garbage

 

Chapter 14 - A Better Painting Framework (GDI+)

 

 

 

 

 

 

collection services in Chapter 4.

 

 

 

Chapter 15 - Programming with Windows Forms Controls

 

 

 

 

 

ChapterMemberwiseClone()16 - The System.IO NamespaceThis protected method exists to return a new object that is a member-

 

 

Chapter 17 - Data Access withbyADO.NET-member copy of the current object. Thus, if your object contains

 

Part Five - Web Applications andreferencesXML WebtoServicesother objects, the references to these types are copied

 

Chapter 18 - ASP.NET Web Pages(i.e.,anda shallowWeb Controlscopy). If the object contains value types, full copies of

 

 

 

Chapter 19 - ASP.NET Web

 

the values are achieved.

 

 

 

Applications

 

 

 

 

 

 

 

 

 

 

Chapter 20 - XML Web Services

To illustrate some of the default behavior provided by the System.Object base class, consider the

Index

following class definition:

List of Figures

List of Tables

// Create some objects and exercise the inherited System.Object methods.

using System;

class ObjTest

{

public static int Main(string[] args)

{

// Make an instance of ObjTest.

ObjTest c1 = new ObjTest();

// Pump info to console.

Console.WriteLine("ToString: {0} ", c1.ToString()); Console.WriteLine("Hash code: {0} ", c1.GetHashCode()); Console.WriteLine("Base class: {0} ", c1.GetType().BaseType);

// Make some other references to c1.

ObjTest c2 = c1;

object o = c2;

// Are all 3 instances pointing to the same object in memory?

C# and the .NET Platform, Second Edition if(o.Equals(c1) && c2.Equals(o))

by Andrew Troelsen ISBN:1590590554

Console.WriteLine("Same instance!");

 

 

Apress © 2003 (1200 pages)

 

}

return 0;

 

This comprehensive text starts with a brief overview of the

}

C# language and then quickly moves to key technical and

 

 

architectural issues for .NET developers.

 

 

Figure 3-11 shows a test run.

Table of Contents

C# and the .NET Platform, Second Edition

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Figure 3-11: Default implementation of select System.Object members

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

First, notice how the default implementation of ToString() simply returns the name of the current type

Part Three - Programming with .NET Assemblies

(ObjTest). In many situations, derived classes override this method to return a string representing the

Chapter 9 - Understanding .NET Assemblies

values of its internal state data (as you do in a moment). GetType() retrieves a System.Type object, which

Chapter 10 - Processes, AppDomains, Contexts, and Threads

defines a property named BaseType (as you can guess, this will identify the fully qualified name of the

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming type's base class). Now, examine the following block of code:

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

// Compare object references...

Chapter 13 - Building a Better Window (Introducing Windows Forms) public static int Main(string[] args)

Chapter 14 - A Better Painting Framework (GDI+)

{

Chapter 15 - Programming with Windows Forms Controls

// Make an instance of ObjTest.

Chapter 16 - The System.IO Namespace

ObjTest c1 = new ObjTest();

Chapter ...17 - Data Access with ADO.NET

Part Five//- WebMakeApplicationssome otherand XMLreferencesW b Servicesto c1.

Chapter

Chapter

Chapter

Index

ObjTest18 - ASP.NETc2Web= c1;Pages and Web Controls

object19 - ASP.NETo =Webc2;Applications

// Are all 3 pointing to the same object in memory?

20 - XML Web Servinstances

if(o.Equals(c1) && c2.Equals(o))

List of Figures Console.WriteLine("Same instance!");

return 0;

List of Tables

}

The default behavior of Equals() is to compare two objects' variables using referencesemantics not value semantics. Here, you create a new ObjTest variable named c1. At this point, a new ObjTest is placed on the managed heap. C2 is also of type ObjTest. However, you are not creating a new instance, but rather assigning this variable to reference c1. Therefore, c1 and c2 are both pointing to the same object in memory, as is the variable o (of type object, which was thrown in for good measure). Given that c1, c2 and o all point to the same object in memory, the equality test succeeds.

Overriding Some Default Behaviors of System.Object

Although the canned behavior of System.Object can fit the bill in a number of cases, it is quite common for your custom types to override some of these inherited methods. Chapter 4 provides a complete examination of OOP under C#, but in a nutshell, overriding is the process of redefining the behavior of an

inherited virtual member in a derived class. As you have just seen, System.Object defines a number of

C# and the .NET Platform, Second Edition

virtual methods (such as ToString() and Equals()) that do define a canned implementation. However, if

by Andrew Troelsen ISBN:1590590554

you want to build a custom implementation of these virtual members for a derived type, you make use of

Apress © 2003 (1200 pages)

the C# "override" keyword.

This comprehensive text starts with a brief overview of the

To illustrate, assumeC# languageyou haveanda Personthen quicklyclassmovesthat definesto keysometechnicalstateanddata representing an individual's

architectural issues for .NET developers. name, social security number, and age:

// Remember! All classes implicitly derive from System.Object.

Table of Contents

class Person

C# and the .NET Platform, Second Edition

{

Introduction

public Person(string fname, string lname, string ssn, byte a)

Part One - Introducing C# and the .NET Platform

{

Chapter 1 - The Philosophy of .NET firstName = fname;

Chapter 2 - Building C# Applications lastName = lname;

Part Two - The C# Programming Language

SSN = ssn;

Chapter 3 - C# Language Fundamentals age = a;

Chapter 4 - Object-Oriented Programming with C#

}

Chapter 5 - Exceptions and Object Lifetime public Person(){}

Chapter 6 - Interfaces and Collections

// The state of a person.

Chapter 7 - Callback Interfaces, Delegates, and Events

public string firstName;

Chapter 8public- AdvancedstringC# TypelastName;Construction Techniques

Part Threepublic- ProgrammingstringwithSS.NET; Assemblies

Chapter 9public- Understandingbyte age;.NET Assemblies

Chapter} 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

ChaptOverridingr 12 - ObjectToString()Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

ChaptTo begin,r 14 let's- A BetteroverridePaintingSystemFramework.Object.ToString()(GDI+) to return a textual representation of a person's state:

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

// Need to reference this namespace to access StringBuilder type.

Chapterusing17System- Data.AccessText;with ADO.NET

Part// FiveA Person- Web Appclassicationsimplementsand XML WebToString()Services as so:

Chapterclass18Person- ASP.NET Web Pages and Web Controls

Chapter{ 19 - ASP.NET Web Applications

// Overriding System.Object.ToString().

Chapter 20 - XML Web Services

Index public override string ToString()

{

List of Figures

List of Tables

}

...

}

StringBuilder sb = new StringBuilder(); sb.AppendFormat("[FirstName= {0}", this.firstName); sb.AppendFormat(" LastName= {0}", this.lastName); sb.AppendFormat(" SSN= {0}", this.SSN); sb.AppendFormat(" Age= {0}]", this.age);

return sb.ToString();

How you choose to format the string returned from System.Object.ToString() is largely a matter of personal choice. In this example, the name/value pairs have been contained within square brackets ([...]). Also notice that this example makes use of a new type, System.Text.StringBuilder (which is also a matter of personal choice). This type is described in greater detail later in the chapter. The short answer, however, is that this type is typically a more efficient alternative to System.String, given that you have direct access to the underlying buffer of character data.

C# and the .NET Platform, Second Edition

 

Overriding Equals()

ISBN:1590590554

by Andrew Troelsen

Apress © 2003 (1200 pages)

Let's also override the behavior of System.Object.Equals() to work with value-basedsemantics. Recall

This comprehensive text starts with a brief overview of the

that by default, Equals() returns true only if the two references being compared are referencing the same

C# language and then quickly moves to key technical and

object in memory. For our Person class, it may be helpful to implement Equals() to return true if the two architectural issues for .NET developers.

variables being compared contain the same state values (e.g., name, SSN, and age):

Table// Aof PersonContentsclass implements Equals() as so:

C#classand thePerson.NET Platform, Second Edition

{

Introduction

public override bool Equals(object o)

Part One - Introducing C# and the .NET Platform

{

Chapter 1 - The Philosophy of .NET

// Does the incoming object instance have the same values as me?

Chapter 2 - Building C# Applications

Person temp = (Person)o;

Part Two - The C# Programming Language

if(temp.firstName == this.firstName &&

Chapter 3 - C# Language Fundamentals

temp.lastName == this.lastName &&

Chapter 4 - Object-Oriented Programming with C#

temp.SSN == this.SSN &&

Chapter 5 - Exceptions and Object Lifetime temp.age == this.age)

Chapter 6 - Interfaces and Collections return true;

Chapter 7 - Callback Interfaces, Delegates, and Events else

Chapter 8 - Advanced C# Type Construction Techniques return false;

Part Three - Programming with .NET Assemblies

}

Chapter 9 - Understanding .NET Assemblies

...

Chapter 10 - Processes, AppDomains, Contexts, and Threads

}

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

ChapterHere you12 are- ObjectexaminingSerializationthe valuesand theof the.NETincomingRe otingobjectLayeragainst the values of our internal values (note

the use of the "this" keyword, which refers to the current object). If the name, SSN, and age of each are

Chapter 13 - Building a Better Window (Introducing Windows Forms)

identical, you have two objects with the exact same state data and therefore return true.

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

The prototype of System.Object.Equals() takes a single argument of type object. Thus, we are required to

Chapter 16 - The System.IO Namespace

perform an explicit cast (further examined in Chapter 4) within the Equals() method to access the

Chapter 17 - Data Access with ADO.NET

members of the Person type. Now, for the sake of argument, assume that an object user passed in a Car

Part Five - Web Applications and XML Web Services

object to the Equals() method as so:

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

// Cars are not people!

Chapter 20 - XML Web Services

Car c = new Car();

Index

Person p = new Person();

List of Figures

p.Equals(c);

List of Tables

This is obviously a problem. In fact, if this was attempted, an InvalidCastException would be thrown by the runtime. Furthermore, what if the end user passed in a null object reference to the Equals() method as follows:

// Forgot to create the Person!

Person theGhost = null;

p.Equals(theGhost);

To design a more bullet-proof Equals() method, you would do well to check for a null value on the incoming parameter, as well as wrap the explicit cast logic within a try / catch statement. I'll examine structured exception handling in Chapter 4, so for the time being, let's assume that the world is a perfect place and the object user will only pass in like-minded (and allocated) types.

// NOTE: We want these to be identical to test the Equals() method.
C# language and then quickly moves to key technical and
Apress © 2003 (1200 pages)

Overriding GetHashCode()

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Before you see the output of this modified Person type, you have one final detail to attend to. When a class

overrides the Equals() method, you should also override the default implementation of GetHashCode() (if

This comprehensive text starts with a brief overview of the

you do not, you are issued a compiler warning). This method returns a numerical value used to identify an

object in memory, and is commonly used with hash-based collections. architectural issues for .NET developers.

Under the hood, if you place a custom object into a System.Collections.Hashtable type, its Equals() and

GetHashCode() members will be called behind the scenes to determine the correct type to return from the

Table of Contents

container. Given this factoid, your custom types should redefine the hashing algorithm used to identify itself

C# and the .NET Platform, Second Edition within such a type.

Introduction

Part One - Introducing C# and the .NET Platform

There are many algorithms that can be used to create a hash code, some fancy, others not so fancy. In

Chapter 1 - The Philosophy of .NET

the simplest case, an object's hash value will be generated by taking its state data into consideration, and

Chapterbuilding2a -uniqueBuildingnumericalC# Applicationsidentifier for the type. For our purposes, let's assume that the hash code of the

PartstringTworepresenting- The C# Programmingan individual'sLanguageSSN is unique enough. System.String has a very solid implementation of

GetHashCode(). Therefore if you have a string member that should be unique among objects (such as an

Chapter 3

- C# Language Fundamentals

ChapterSSN), this4

-isObjectan elegant-Orientedsolution:Pr gramming with C#

Chapter 5

- Exceptions and Object Lifetime

Chapter 6

-

and Collections

// ReturnInterfaceshash code based on the person's SSN.

Chapter 7

- Callback Interfac s, Delegates, and Events

publicoverride

int GetHashCode()

Chapter{

8

- Advanced C# Type Construction Techniques

Part Threereturn- P ogrammingSSN.GetHashCodewith .NET Assemblies();

Chapter} 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

With this, here is our new Person class in action (check out Figure 3-12 for output):

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

// Make a few people and play with the overridden Object methods.

Chapter 13 - Building a Better Window (Introducing Windows Forms)

public static int Main(string[] args)

Chapter 14 - A Better Painting Framework (GDI+)

{

Chapter 15 - Programming with Windows Forms Controls

...

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Person p1 = new Person("Fred", "Jones", "222-22-2222", 98);

Part Five - Web Applications and XML Web Services

Person p2 = new Person("Fred", "Jones", "222-22-2222", 98);

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

// Equals() now uses value semantics.

Chapter 20 - XML Web Services

// As well, given that each object has the same SSN, they should have Index // the same hash-code (given the work performed by System.String).

List of Figures

= p2.GetHashCode())

if(p1.Equals(p2) && p1.GetHashCode() =

List of Tables Console.WriteLine("P1 and P2 have

same state\ n");

else

 

Console.WriteLine("P1 and P2 are DIFFERENT\ n");

// Change state of p2.

Console.WriteLine("Changing the age of p2"); p2.age = 2;

// Test again.

if(p1.Equals(p2) && p1.GetHashCode() = = p2.GetHashCode()) Console.WriteLine("P1 and P2 have same state\ n");

else

Console.WriteLine("P1 and P2 are DIFFERENT\ n");

// Get 'stringified' version of objects.

Console.WriteLine("Stringified people!");

Console.WriteLine(p1.ToString());

Console.WriteLine(p2);

// ToString() called automatically

return 0;

}

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the key technical and

Table

C# and

IntroductionFigure 3-12: Overridden System.Object members in action

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

ChapterStatic2 Members- Building C# Applicationsof System.Object

Part Two - The C# Programming Language

ChapterIn addition3 -toC#theLainstanceguage Fundamentals-level members you have just examined, System.Object does define two static

members (Object.Equals() and Object.ReferenceEquals()) that also test for value-based or reference-

Chapter 4 - Object-Oriented Programming with C#

based equality. Consider the following code:

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter// Static7 - CallbackmembersInterfaces,of SystemDel gates,.Objectand Events.

Person p3 = new Person("Sally", "Jones","333", 4);

Chapter 8 - Adva ced C# Type Construction Techniques

Person p4 = new Person("Sally", "Jones","333", 4);

Part Three - Programming with .NET Assemblies

// Do P3 and P4 have the same state? TRUE!

Chapter 9 - Understanding .NET Assemblies

Console.WriteLine("P3 and P4 have same state: {0} ", object.Equals(p3, p4));

Chapter 10 - Processes, AppDomains, Contexts, and Threads

// Are they the same object in memory? FALSE!

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Console.WriteLine("P3 and P4 are pointing to same object: {0} ",

Part Four - Leveraging the .NET Libraries

object.ReferenceEquals(p3, p4));

Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Here, you are able to simply send in two objects (of any type) and allow the System.Object class to

Chapter 15 - Programming with Windows Forms Controls determine the details automatically.

Chapter 16 - The System.IO Namespace

Excellent! At this point you have a solid understanding of the topmost base class in the .NET class

Chapter 17 - Data Access with ADO.NET

hierarchy. Understand that every class, structure, enumeration, and delegate defined in the .NET base

Part Five - Web Applications and XML Web Services

class libraries are always guaranteed to support the public members of System.Object (interface types

Chapter 18 - ASP.NET Web Pages and Web Controls

however, do not derive from System.Object, or any base class for that matter). Next up, let's examine the

Chapter 19 - ASP.NET Web Applications

C# intrinsic data types in a bit more detail.

Chapter 20 - XML Web Services

IndexSOURCE The ObjectMethods project is located under the Chapter 3 subdirectory.

List of Figures

CODE

List of Tables

The SystemC#Dataand theTypes.NET Platform,(and C#SecondAliases)Edition

by Andrew Troelsen

ISBN:1590590554

As you may have begun to notice, every intrinsic C# data type is actually an alias to an existing type defined in

Apress © 2003 (1200 pages)

the System namespace. Specifically, each C# data type aliases a well-defined structure type in the System

This comprehensive text starts with a brief overview of the namespace.TableC#3-language4 lists eachandsystemthen quicklydata type,movesitstorange,key technicalthe correspondingand C# alias, and the type's

compliance with thearchitecturalCommonissuesLanguagefor .NETSpecificationdevelopers.(CLS).

Table 3-4: System Types and C# Aliases

Table of Contents

 

SystemEdition Type

 

Range

 

Meaning

C#C#and the .NETCLSPlatform, Second

 

 

 

IntroductionAlias

 

Compliant?

 

 

 

 

 

in Life

 

 

 

 

 

 

 

 

 

 

 

Part One -

Introducing C# and the .NET Platform

 

-128 to 127

 

Signed 8-bit

 

 

sbyte

 

No

 

System.SByte

 

 

Chapter 1 -

The Philosophy of .NET

 

 

 

number.

 

 

 

 

 

 

 

 

 

 

Chapter 2 - Building C# Applications

PartbyteTwo - TheYesC# Programming LanguageSystem.Byte

Chapter 3

- C# Language Fundamentals

Chapter 4

- Object-Oriented Programming with C#

short

Yes

System.Int16

Chapter 5

- Exceptions and Object Lifetime

0 to 255

-32,768 to 32,767

Unsigned 8- bit number.

Signed 16-bit number.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Chapter

6

-

 

 

 

Interfaces and Collections

 

0 to 65,535

 

Unsigned 16-

 

ushort

-

 

 

 

No

 

System.UInt16

 

 

 

Chapter

7

 

 

 

Callback Interfaces, Delegates, and Events

 

 

bit number.

 

Chapter

8

-

 

 

 

Advanced C# Type

 

Construction Techniques

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Part Three -

 

 

 

Programming with

 

.NET Assemblies

 

-2,147,483,648 to 2,147,483,647

 

Signed 32-bit

 

int

 

 

 

 

 

Yes

 

System.Int32

 

 

Chapter

9

-

 

 

 

Understanding .NET

 

Assemblies

 

 

 

number.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Chapter

10

-

 

 

Processes, AppDomains, Contexts, and

 

Threads

 

Unsigned 32-

 

uint

11

-

 

 

 

No

 

System.UInt32

 

0 to 4,294,967,295

 

 

Chapter

 

 

 

Type Reflection, Late Binding, and Attribute-Based Programming

 

bit number.

Part Four -

 

 

 

Leveraging the .NET

 

Libraries

 

 

 

 

 

 

 

 

 

 

 

 

long

12

-

 

 

 

Yes

 

System.Int64

 

-9,223,372,036,854,775,808 to

 

Signed 64-bit

 

Chapter

 

 

 

Object Serialization

 

and he .NET Remoting

Layer

 

 

 

Chapter

13

-

 

 

 

Building a Better

Window (Introducing

Windows9,223,372,036,854,775,807Forms)

 

number.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Chapter

14

-

 

A Better Painting

 

Framework (GDI+)

 

0 to 18,446,744,073,709,551,615

 

Unsigned 64-

 

ulong

-

 

 

 

No

 

System.UInt64

 

 

 

Chapter

15

 

Programming with

 

Windows Forms Controls

 

bit number.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Chapter

16

-

 

 

 

The System.IO Namespace

 

 

 

 

 

 

 

 

 

 

 

 

 

Chapterchar

17

-

 

 

 

DataYesAccess with ADO.NETSystem.Char

 

U10000 to U1ffff

 

A single 16-

Part Five - Web Applications and XML Web Services

 

 

 

bit Unicode

 

Chapter

18

-

 

ASP.NET Web Pages

 

and Web Controls

 

 

 

character.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Chapter

19

-

 

 

 

ASP.NET Web Applications

 

1.5x10-45 to 3.4x1038

 

32-bit floating

 

float

 

 

 

 

 

Yes

 

System.Single

 

 

 

Chapter

20

-

 

 

 

XML Web Services

 

 

 

 

 

point number.

Index

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Yes

 

System.Double

 

5.0x10-324 to 1.7x10308

 

64-bit floating

 

double

 

 

 

 

 

 

 

List of Figures

 

 

 

 

 

 

 

 

 

point number.

List of Tables

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

bool

 

 

 

 

 

Yes

 

System.Boolean

 

true or false

 

Represents

 

 

 

 

 

 

 

 

 

 

 

 

 

truth or

 

 

 

 

 

 

 

 

 

 

 

 

 

falsity.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

decimal

 

 

 

 

Yes

 

System.Decimal

 

100 to 1028

 

A 96-bit

 

 

 

 

 

 

 

 

 

 

 

 

 

signed

 

 

 

 

 

 

 

 

 

 

 

 

 

number.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

string

 

 

 

 

 

Yes

 

System.String

 

Limited by system memory.

 

Represents a

 

 

 

 

 

 

 

 

 

 

 

 

 

set of

 

 

 

 

 

 

 

 

 

 

 

 

 

Unicode

 

 

 

 

 

 

 

 

 

 

 

 

 

characters.

 

 

 

 

 

 

 

 

 

 

 

 

object

 

YesC# and the

.NETSystem.ObjectPlatform, SecondAnythingEditionat all. All types (not

 

The base

 

 

 

 

by Andrew Troelsen

 

including interfaces) derive from

 

class of all

 

 

 

 

 

ISBN:1590590554

 

 

 

 

 

 

Apress © 2003 (1200 pages)

 

object. Therefore, everything is

 

types in the

 

 

 

 

 

 

 

 

an object.

 

.NET

 

 

 

 

This comprehensive text starts with a brief overview of the

 

universe.

 

 

 

 

C# language

and then quickly moves to key technical and

 

 

 

 

 

 

 

 

 

 

 

 

 

architectural issues for .NET developers.

The relationship between these core system types (as well as some other soon-to-be-discovered types) can Tablebe understoodof Contentsas shown in Figure 3-13.

C# and the .NET Platform, Second Edition

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Programming

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Figure 3-13: The hierarchy of System types

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

As you can see, each of these types ultimately derives from System.Object. Thus, because data types such as

Chapter 19 - ASP.NET Web Applications

"int" are simply shorthand notations for the corresponding system type (in this case System.Int32), the

Chapter 20 - XML Web Services following is perfectly legal syntax:

Index

List of Figures

// Remember! A C# int is really an alias for System.Int32.

List of Tables

Console.WriteLine(12.GetHashCode());

Console.WriteLine(12.GetType().BaseType);

Also notice that although C# defines a number of data types, only a subset of the whole are compliant with the rules of the CLS. When you build custom types that must work seamlessly across all languages, you must stick to this well-defined subset. The basic rule of thumb is to avoid exposing unsigned types when defining any public member of a type definition (as seen in Chapter 1). By doing so, you ensure that your custom classes, interfaces, and structures can be understood by any language targeting the .NET runtime.

Experimenting with the System Data Types

As you have seen, C# data types alias a related structure in the System namespace (and thus derive from System.ValueType). Functionally, the only purpose of System.ValueType is to override the virtual methods defined by System.Object to work with value-based versus reference-based semantics. In fact, the signatures

of the instance methods defined by System.ValueType are identical to those of System.Object:

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

// Behold the immediate base class for all .NET structures and enums.

Apress © 2003 (1200 pages)

public abstract class ValueType : object

This comprehensive text starts with a brief overview of the

{

C# language and then quickly moves to key technical and

public virtual bool Equals(object obj); architectural issues for .NET developers.

public virtual int GetHashCode();

public Type GetType();

Table ofpublicContentsvirtual string ToString();

}

C# and the .NET Platform, Second Edition

Introduction

Part One - Introducing C# and the .NET Platform

Given your understanding of System.ValueType, it should be clear that when you compare two intrinsic data

Chapter 1 - The Philosophy of .NET

types for equality, you are using value-based semantics:

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

// Test value semantics.

Chapter 3 - C# Language Fundamentals

ChapterSystem.Int324 - ObjectintA-Oriented= 1000;Programming with C#//

Same

as: int intA = 1000;

ChapterSystem.Int325 - ExceptionsintBand= Object1000;Lifetime

//

Same

as int intB = 1000;

// The test succeeds! The two instances contain the same value.

Chapter 6 - Interfaces and Collections if(intA == intB)

Chapter 7 - Callback Interfaces, Delegates, and Events

Console.WriteLine("Same value!");

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

ChapterThe structures9 - Understandingthat represent.NETtheAssembliesC# intrinsic data types (e.g., System.Int32, System.Char, System.Boolean,

Chapterand so10on)-alsoPr cesses,supportAppDomains,set of helpfulContexts,static andmembersThreads. While I assume you will consult online Help for full

Chapterdetails,11let's- TypecheckReflectiout somen, LateselectBinding,pointsandof inAttribuerest.e-Based Programming

Part Four - Leveraging the .NET Libraries

ChapterBasic12 Numerical- Object Seri lizationMembersand the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

ChapFirsterof14all,-understandA B tter Paintingthat theFramewonumericalk (GDI+)types support MaxValue and MinValue properties that provide

Chapterinformation15 - regardingProg ammingthewithminimumWindowsandFormsmaximumControlsvalue a given type can hold. Assume you have created Chaptsomervariables16 - The ofSystemtype .SystemIO Namespace.UInt16, and exercised it as follows:

Chapter 17 - Data Access with ADO.NET

Part// FiveNote- WebthatApplicatan implicitons and XMLdataWeb Servicestype (ushort) has the same methods available as

Chapter// the18corresponding- ASP.NET Web Pageswrappernd Web(SystemControls .UInt16).

Chapterclass19MyDataTypes- ASP.NET Web Applications

Chapter{ 20 - XML Web Services

Index public static int Main(string[] args)

{

List of Figures

List of Tables

}

}

System.UInt16 myUInt16 = 30000;

Console.WriteLine("Max for an UInt16 is: {0} ", UInt16.MaxValue); Console.WriteLine("Min for an UInt16 is: {0} ", UInt16.MinValue); Console.WriteLine("Value is: {0} ", myUInt16); Console.WriteLine("I am a: {0} ", myUInt16.GetType().ToString());

// Now in System.UInt16 shorthand (e.g. a ushort).

ushort myOtherUInt16 = 12000;

Console.WriteLine("Max for an UInt16 is: {0} ", ushort.MaxValue); Console.WriteLine("Min for an UInt16 is: {0} ", ushort.MinValue); Console.WriteLine("Value is: {0} ", myOtherUInt16); Console.WriteLine("I am a: {0} ", myOtherUInt16.GetType().ToString()); return 0;

In addition to the MinValue / MaxValue properties, a given system type may define further useful members. For

example, System.Double type allows you to obtain the values for Epsilon, and infinity values:

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Console.WriteLine("-> double.Epsilon: {0}", double.Epsilon);

Apress © 2003 (1200 pages)

Console.WriteLine("-> double.PositiveInfinity: {0}", double.PositiveInfinity);

This comprehensive text starts with a brief overview of the

Console.WriteLine("-> double.NegativeInfinity: {0}", double.NegativeInfinity);

C# language and then quickly moves to key technical and

Console.WriteLine("-> double.MaxValue: {0}", double.MaxValue); architectural issues for .NET developers.

Console.WriteLine("-> double.MinValue: {0}",double.MinValue);

Table of Contents

C#Membersand the .NET ofPlatform,SystemSecond.BooleanEditi n

Introduction

PartNext,Oneconsider- Introducingthe SystemC# and.Booleanthe .NETdataPl typeform. Unlike C(++), the only valid assignment a C# bool can take is

Chapterfrom the1 set- The{truePhilosophy| false}. Youof .NETcannot assign makeshift values (e.g., -1, 0, 1) to a C# bool, which (to most

Chapterprogrammers)2 - Buildingis a welcomeC# Applicatiochanges . Given this point, it should be clear that System.Boolean does not support

PartMinValue/MaxValueTwo - The C# ProgrammingpropertyLanguageset, but rather TrueString/FalseString:

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

// No more ad hoc Boolean types in C#!

Chapterbool b5 =- Exceptions0; and//ObjectIllegal!Lifetime

Chapterbool b26 -=Interfaces-1; and //CollectionsAlso illegal!

Chapterbool b37 -=Callbacktrue;Interfaces,// NoDelegates,problemand. Events

bool b4 = false; // No problem.

Chapter 8 - Adv nced C# Type C nst uction Techniques

Console.WriteLine("-> bool.FalseString: {0}", bool.FalseString);

Part Three - Programming with .NET Assemblies

Console.WriteLine("-> bool.TrueString: {0}", bool.TrueString);

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

ChapterMembers12 - ObjectofSerializationSystem.andCharthe .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

It is important to note that C# textual data is represented by the intrinsic C# string and char data types. Thus,

Chapter 14 - A Better Painting Framework (GDI+)

no more nasty char*, wchar_t*, LPSTR, LPCSTR, BSTR or OLECHAR string types! I am sure you agree with

Chapter 15 - Programming with Windows Forms Controls

me that string manipulation in the COM and Win32 universe was horrifying. Utterly and completely horrifying.

Chapter 16 - The System.IO Namespace

On a happy note, .NET offers a very simplified view of string management, as all .NET-aware languages map

Chapter 17 - Data Access with ADO.NET

textual data to the same underlying types (System.String and System.Char), both of which are Unicode under

Part Five - Web Applications and XML Web Services

the hood.

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

The System.Char type (represented by the C# "char" keyword) provides you with a great deal of functionality

Chapter 20 - XML Web Services

beyond the ability to hold a single point of character data (which must be placed between single tick marks). IndexMore interestingly, using the static methods of System.Char, you are able to determine if a given character is

Listnumerical,of Figuresalphabetical, a point of punctuation, or whatnot. To illustrate, check out the following:

List of Tables

// Test the truth or falsity of the following statements...

Console.WriteLine("-> char.IsDigit('K'): {0}", char.IsDigit('K')); Console.WriteLine("-> char.IsDigit('9'): {0}", char.IsDigit('9')); Console.WriteLine("-> char.IsLetter('10', 1): {0}", char.IsLetter("10", 1)); Console.WriteLine("-> char.IsLetter('p'): {0}", char.IsLetter('p')); Console.WriteLine("-> char.IsWhiteSpace('Hello There', 5): {0}",

char.IsWhiteSpace("Hello There", 5));

Console.WriteLine("-> char.IsWhiteSpace('Hello There', 6): {0}", char.IsWhiteSpace("Hello There", 6));

Console.WriteLine("-> char.IsLetterOrDigit('?'): {0}",

char.IsLetterOrDigit('?'));

Console.WriteLine("-> char.IsPunctuation('!'): {0}",

char.IsPunctuation('!'));

Console.WriteLine("-> char.IsPunctuation('>'): {0}",

char.IsPunctuation('>'));

Console.WriteLine("-> char.IsPunctuation(','): {0}",

C# and the .NET Platform, Second Edition char.IsPunctuation(','));

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

As you can see, eachThis cofmprehensivethese static textmembersstarts withof Systema brief.Charoverviewhas oftwothecalling conventions: a single character or a string with a C#numericallanguageindexand thatthenspecifiedqui kly movesthe positionto key oftecthenicalcharacternd to test.

architectural issues for .NET developers.

Parsing Values from String Data

Table of Contents

Finally, also understand that the .NET data types provide the ability to generate a variable of their underlying

C# and the .NET Platform, Second Edition

type given a textual equivalent (e.g., parsing). This technique can be extremely helpful when you wish to

Introduction

convert a bit of user input data (such as a listbox selection) into a numerical value. Ponder the following

Part One - Introducing C# and the .NET Platform

parsing logic:

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

bool myBool = bool.Parse("True");

Part Two - The C# Programming Language

Console.WriteLine("-> Value of myBool: {0}", myBool);

Chapter 3 - C# Language Fundamentals

double myDbl = double.Parse("99.884");

Chapter 4 - Object-Oriented Programming with C#

Console.WriteLine("-> Value of myDbl: {0}", myDbl);

Chapter 5 - Exceptions and Object Lifetime int myInt = int.Parse("8");

Chapter 6 - Interfaces and Collections

Console.WriteLine("-> Value of myInt: {0}", myInt);

Chapter 7 - Callback Interfaces, Delegates, and Events char myChar = char.Parse("w");

Chapter 8 - Advanced C# Type Construction Techniques

Console.WriteLine("-> Value of myChar: {0}\n", myChar);

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

ChapterSOURCE11 - Type Reflection,The DataTypesL te Binding,projectandisAttributelocated-BasedunderProgrammingthe Chapter 3 subdirectory.

Part FourCODE- Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

ConvertingC#Betweenand the .NETValueP atform,TypesSecondandEditionReference Types: Boxing and

Unboxing by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

 

This comprehensive text starts with a brief overview of the

Given that .NET defines two broad categories of types (value-based and reference-based), you may

C# language and then quickly moves to key technical and

occasionally need to represent a variable of one category as a variable of the other category. C# provides a architectural issues for .NET developers.

very simple mechanism to convert between value types and reference types, termed boxing. To illustrate, assume that you have created a simple value data type of type short:

Table of Contents

// Make a simple value data point.

C# and the .NET Platform, Second Edi ion

short s = 25;

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

If, during the course of your application, you wish to represent this value type as a reference type, you would

Chapter 2 - Building C# Applications

"box" the value as follows:

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

// Box the value into an object reference.

Chapter 4 - Object-Oriented Programming with C#

object objShort = s;

Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Boxing can be formally defined as the process of explicitly converting a value type into a corresponding

Chapter 8 - Advanced C# Type Construction Techniques

reference type. When you box a value, essentially all you are doing is allocating a new object on the heap and PartcopyingThreethe- Programminginternal valuewith(in this.NETcaseA semblies25) into that instance. What is returned to you is a true-blue reference to Chapterthe newly9 allocated- Understandingobject..NETUsingAssembliesthis technique, .NET developers have no need to make use of a set of

Chapterwrapper10classes- Procesuseds, AppDomains,to temporarilyContexts,treat intrinsicand Threadsdata as heap-allocated objects (as is the case in Java).

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

The opposite operation is also permitted through unboxing. Unboxing is the term given to the process of

Part Four - Leveraging the .NET Libraries

converting the value held in the object reference back into a corresponding value type on the stack. The

Chapter 12 - Object Serialization and the .NET Remoting Layer

unboxing operation begins by verifying that the receiving data type is equivalent to the boxed type, and if so,

Chapter 13 - Building a Better Window (Introducing Windows Forms)

copying the value out of the box into a local stack based variable. For example, the following unboxing operatio

Chapter 14 - A Better Painting Framework (GDI+)

works successfully, given that the underlying type of the objShort is indeed a "short":

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

// Now, unbox the reference back into a corresponding short.

Chapter 17 - Data Access with ADO.NET

short anotherShort = (short)objShort;

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Again, it is critical that you unbox into an appropriate data type. Thus, the following unboxing logic generates an

Index

InvalidCastException exception (you examine casting and exception handling in detail in the next chapter, so

Listholdof tightFiguresfor now):

List of Tables

// Bad unboxing!

public static int Main(string[] args)

{

...

try

{

// The type contained in the box is NOT a string, but a short!

string str = (string)objShort;

}

catch(InvalidCastException e)

{

Console.WriteLine("OOPS!\n{0} ", e.ToString());

}

}

Some PracticalC# (Un)boxingand the .NET PlatforExamples, S cond Edition

by Andrew Troelsen

ISBN:1590590554

So, you may be thinking, when would you really need to manually box (or unbox) a data type? The previous

Apress © 2003 (1200 pages)

example was purely illustrative in nature, as there was no good reason to box (and then unbox) the short data

This comprehensive text starts with a brief overview of the

point. The truth of the matter is that you will seldom need to manually box data types, if ever. Much of the time,

C# language and then quickly moves to key technical and the C# compiler automaticallyrchitec ural issuesboxesforvariables.NET developerswhen appropriate. .

For example, if you pass a value type into a method requiring an object parameter, boxing occurs behind the

curtains. However, if you wish to invoke members of the underlying value type, you will be required to perform

Table of Contents

an explicit unboxing operation. To illustrate, ponder the following:

C# and the .NET Platform, Second Edition

Introduction

PartclassOne -BoxerIntroducing C# and the .NET Platform

Chapter{ 1 - The Philosophy of .NET

// Helper f(x) to illustrate automatic boxing.

Chapter 2 - Building C# Applicat ons

public static void UseThisObject(object o)

Part Two - The C# Programming Language

Chapter{3 - C# Language Fundamentals

Console.WriteLine(o.GetType());

Chapter 4 - Object-Oriented Programming with C#

Console.WriteLine(o.ToString());

Chapter 5 - Exceptions and Object Lifetime

Console.WriteLine("Value of o is: {0}", o);

Chapter 6 - Interfaces and Collections

// Need to explicitly unbox to get at members of

Chapter 7 - Callback Interfaces, Delegates, and Events

// System.Int32. (GetTypeCode() returns a value

Chapter 8 - Advanced C# Type Construction Techniques

// representing the underlying "type of intrinsic type".

Part Three - Programming with .NET Assemblies

Console.WriteLine(((int)o).GetTypeCode());

Chapter 9 - Understanding .NET Assemblies

}

Chapter 10 - Processes, AppDomains, Contexts, and Threads static void Main(string[] args)

Chapter{11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

int x = 99;

Chapter 12 - Object Serialization and the .NET Remoting Layer

UseThisObject(x); // Automatic boxing.

Chapter}13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

}

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

In addition to the automatic boxing performed when calling custom functions, boxing implicitly occurs when

Part Five - Web Applications and XML Web Services

interacting with numerous types of the .NET base class libraries. For example, the System.Collections

Chapter 18 - ASP.NET Web Pages and Web Controls

namespace (further examined in Chapter 6) defines a type named ArrayList. Like most collection types,

Chapter 19 - ASP.NET Web Applications

ArrayList provides members that allow you to insert, index, and remove items. If you were to check the formal

Chapter 20 - XML Web Services

class definition using wincv.exe, you would find prototypes such as:

Index

List of Figures

public class System.Collections.ArrayList : object,

List of Tables

System.Collections.IList,

System.Collections.ICollection,

System.Collections.IEnumerable,

ICloneable

{

...

public virtual int Add(object value);

public virtual void Insert(int index, object value); public virtual void Remove(object obj);

}

As you can see, these members take generic System.Object types as parameters. Given that everything ultimately derives from this common base class, the following code is perfectly legal:

ArrayList myInts = new ArrayList();

C# and the .NET Platform, Second Edition

 

myInts.Add(88);

ISBN:1590590554

by Andrew Troelsen

myInts.Add(3);

 

Apress © 2003 (1200 pages)

 

myInts.Add(9764);

 

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

However, given your understanding of value types and reference types, you might wonder exactly what was placed into the ArrayList type (references, copies of references, (copies of) structures, etc). Just like the

previous Foo() method, it should be clear that each of the System.Int32 data types were indeed boxed before

Table of Contents

being stored into the ArrayList type. As well, just like the Foo() helper method, if you wish to interact with the

C# and the .NET Platform, Second Edition

members of the boxed type, you are required to unbox accordingly. Thus, assume the following static helper

Introduction method:

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

public static void BoxAndUnboxInts()

Chapter 2 - Building C# Applications

{

Part Two - The C# Programming Language

// Box ints into ArrayList.

Chapter 3 - C# Language Fundamentals

ArrayList myInts = new ArrayList();

Chapter 4 - Object-Oriented Programming with C# myInts.Add(88);

Chapter 5 - Exceptions and Object Lifetime myInts.Add(3);

Chapter 6 - Interfaces and Collections

myInts.Add(9764);

Chapter 7 - Callback Interfaces, Delegates, and Events

// Unbox first item.

Chapterint8 -firstItemAdvanced C#=Type(int)myInts[0];Construction Techniques

Part ThreeConsole- Programming.WriteLine("Firstwith .NET A sembliesitem is {0}", firstItem);

Chapter} 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter(Un)Boxing12 - Object UnderSerializationtheand Hoodthe .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

ChapterIf you examine14 - A Betterthe underlyingPainting FrameworkCIL using(GDI+)ildasm.exe for the BoxAndUnboxInts() method, you can clearly see Chapterexactly15when- Programmingthe System.Int32with Windowstypes areFormscopiedControlsfrom the heap to the stack (and vice versa):

Chapter 16 - The System.IO Namespace

Chapter.method17 -publicData A cesshidebysigwith ADO.NETstatic void BoxAndUnboxInts() cil managed

Part{ Five - Web Applications and XML Web Services

Chapter// Code18 - ASPsize.NET Web Pages81and(0x51)Web Controls

Chapter.maxstack19 - ASP.NET3 Web Applications

.locals init ([0] class [mscorlib]System.Collections.ArrayList myInts,

Chapter 20 - XML Web Services

Index

[1] int32 firstItem)

List ILof Figures_0000:

newobj

 

List of Tablesinstance void [mscorlib]System.Collections.ArrayList::.ctor()

IL_0005:

stloc.0

 

IL_0006:

ldloc.0

88

IL_0007:

ldc.i4.s

IL_0009:

box

[mscorlib]System.Int32

IL_000e:

callvirt

 

instance int32 [mscorlib]System.Collections.ArrayList::Add(object)

IL_0013:

pop

 

IL_0014:

ldloc.0

 

IL_0015:

ldc.i4.3

[mscorlib]System.Int32

IL_0016:

box

IL_001b:

callvirt

 

instance int32 [mscorlib]System.Collections.ArrayList::Add(object)

IL_0020:

pop

 

IL_0021:

ldloc.0

0x2624

IL_0022:

ldc.i4

IL_0027:

box

[mscorlib]System.Int32

 

 

C# and the .NET Platform, Second Edition

 

 

IL_002c: callvirt

 

ISBN:1590590554

 

 

by Andrew Troelsen

 

instance int32 [mscorlib]System.Collections.ArrayList::Add(object)

 

IL_0031:

Apress © 2003 (1200 pages)

 

 

pop

 

 

 

IL_0032:

This comprehensive text starts with a brief overview of the

 

ldloc.0

 

 

 

IL_0033:

C# language and then quickly moves to key technical and

 

ldc.i4.0

 

 

 

IL_0034:

architectural issues for .NET developers.

 

 

callvirt

 

 

 

instance object [mscorlib]System.Collections.ArrayList::get_Item(int32)

TableILof_0039:Contentsunbox

[mscorlib]System.Int32

 

C# andIL_the003e:.NET Platform,ldind.i4Second Edition

 

 

IL_003f:

stloc.1

 

 

 

Introduction

 

 

 

 

PartILOne_0040:- IntroducingldstrC# and the .NET"FirstPlatformitem is {0}"

 

 

IL_0045:

ldloc.1

 

 

 

Chapter 1 - The Philosophy of .NET

 

 

IL_0046:

box

[mscorlib]System.Int32

 

Chapter 2 - Building C# Applications

 

object

IL_004b:

call

void [mscorlib]System.Console::WriteLine(string,

Part Two - The C# Programming Language

 

 

IL_0050:

ret

 

 

 

Chapter 3

- C# Language Fundamentals

}

 

Chapter 4

- Object-Oriented Programming with C#

Chapter 5

- Exceptions and Object Lifetime

ChapterHere, we6 have- Interfacindirectlys andtriggeredCollectionsa fourth CIL box operation at the point of printing out the value of the first item

help in the ArrayList. The reason? System.Console.WriteLine() does not supply an overloaded variation that

Chapter 7 - Callback Interface , Delegates, and Events

operates on raw System.Int32 types!

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

To be sure, boxing and unboxing types takes some processing time, and if used without restraint, could hurt the

Chapter 9 - Understanding .NET Assemblies

performance of your application. However, given this .NET technique, you are able to symmetrically operate on

Chapter 10 - Processes, AppDomains, Contexts, and Threads

value-based and reference-based types. Without such a mechanism, we would be forced to be painfully aware

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

of the underlying type of a given variable (which would also result in extraneous code, as we see in C and C++)

Part Four - Leveraging the .NET Libraries

In this light, I'd place my vote that (un)boxing is a positive trait of a mature runtime.

Chapter 12 - Object Serialization and the .NET Remoting Layer

ChapterOn a final13 -boxingBuilding-relatedBetternote,Windowunderstand(Introducingthat if Windowsyou wereFtorms)pass custom structures or enumerations into a Chaptermethod14taking- A BettergenericPaintingSystemFramework.Object parameters,(GDI+) you would also be required to unbox the parameter to

interact with the specific members of the structure (or enum). This topic will be revisited later in this chapter

Chapter 15 - Programming with Wind ws Forms Controls

when you formally examine the C# structure.

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

SOURCE The Boxing project is included under the Chapter 3 subdirectory.

Part Five - Web Applications and XML Web Services

CODE

Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Соседние файлы в предмете Программирование