- •Table of Contents
- •C# and the .NET Platform, Second Edition
- •Introduction
- •Part One: Introducing C# and the .NET Platform
- •Part Two: The C# Programming Language
- •Part Three: Programming with .NET Assemblies
- •Part Four: Leveraging the .NET Libraries
- •Part Five: Web Applications and XML Web Services
- •Obtaining This Book's Source Code
- •The .NET Solution
- •What C# Brings to the Table
- •The Role of the Assembly Manifest
- •Summary
- •Chapter 2: Building C# Applications
- •Summary
- •Chapter 3: C# Language Fundamentals
- •Defining Program Constants
- •Defining Custom Class Methods
- •C# Enumerations
- •Summary
- •The Second Pillar: C#'s Inheritance Support
- •Summary
- •Catching Exceptions
- •Finalizing a Type
- •Garbage Collection Optimizations
- •Summary
- •Chapter 6: Interfaces and Collections
- •Building Comparable Objects (IComparable)
- •Summary
- •Summary
- •Internal Representation of Type Indexers
- •Summary
- •An Overview of .NET Assemblies
- •Understanding Delayed Signing
- •Using a Shared Assembly
- •GAC Internals
- •Summary
- •Spawning Secondary Threads
- •A More Elaborate Threading Example
- •Summary
- •Summary
- •Object Persistence in the .NET Framework
- •The .NET Remoting Namespaces
- •Understanding the .NET Remoting Framework
- •All Together Now!
- •Terms of the .NET Remoting Trade
- •Testing the Remoting Application
- •Revisiting the Activation Mode of WKO Types
- •Deploying the Server to a Remote Machine
- •Summary
- •Control Events
- •The Form Class
- •Summary
- •Regarding the Disposal of System.Drawing Types
- •Understanding the Graphics Class
- •Summary
- •The TextBox Control
- •Working with Panel Controls
- •Configuring a Control's Anchoring Behavior
- •Summary
- •Chapter 16: The System.IO Namespace
- •The Static Members of the Directory Class
- •The Abstract Stream Class
- •Summary
- •The Role of ADO.NET Data Providers
- •The Types of System.Data
- •Selecting a Data Provider
- •The Types of the System.Data.OleDb Namespace
- •Working with the OleDbDataReader
- •Summary
- •Submitting the Form Data (GET and POST)
- •Some Benefits of ASP.NET
- •Creating an ASP.NET Web Application by Hand
- •The Composition of an ASP.NET Page
- •The Derivation of an ASP.NET Page
C# EnumerationsC# and the .NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
Often it is convenient to create a set of symbolic names for underlying numerical values. For example, if
Apress © 2003 (1200 pages)
you are creating an employee payroll system, you may wish to use the constants VP, Manager, Grunt, and
This comprehensive text starts with a brief overview of the
Contractor ratherC#thanlanguageraw numericaland thenvaluesquicklysuchmovesasto{0,key1, 2,technical3}. LikeandC(++), C# supports the notion of custom enumerationsarchitecturalfor thisissuesvery reasonfor .NET. Fordevelopersexample,. here is the EmpType enumeration:
// A custom enumeration.
Table of Contents enum EmpType
C# and the .NET Platform, Second Edition
{
Introduction |
// = 0 |
Manager, |
|
Part One - Introducing C# and the .NET Platform |
|
Grunt, |
// = 1 |
Chapter 1 - The Philosophy of .NET |
|
Contractor, |
// = 2 |
Chapter 2 - Building C# Applications |
|
VP |
// = 3 |
Part Two - The C# Programming Language |
|
} |
|
Chapter 3 - C# Language Fundamentals |
Chapter 4 - Object-Oriented Programming with C#
The EmpType enumeration defines four named constants, corresponding to discrete numerical values. In
Chapter 5 - Exceptions nd Object Lifetime
C#, the numbering scheme sets the first element to zero (0) by default, followed by an n+1 progression.
Chapter 6 - Interfaces and Collections
You are free to change this behavior as you see fit, thus:
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part// ThreeBegin- Programmingnumber atwith102.NET. Assemblies
enum EmpType
Chapter 9 - Understanding .NET Assemblies
{
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Manager = 102,
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Grunt, // = 103
Part Four - Leveraging the .NET Libraries
Contractor, // = 104
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter |
VP13 - Building a Better// Window= 105 (Introducing Windows Forms) |
|
Chapter} |
14 |
- A Better Painting Framework (GDI+) |
Chapter |
15 |
- Programming with Windows Forms Controls |
Chapter |
16 |
- The System.IO Namespace |
Enumerations do not necessarily need to follow a sequential ordering. If (for some reason) it made good |
||
Chapter |
17 |
- Data Access with ADO.NET |
sense to establish your EmpType as seen next, the compiler continues to be happy: |
||
Part Five - Web Applications and XML Web Services |
||
Chapter |
18 |
- ASP.NET Web Pages and Web Controls |
// Elements of an enumeration need not be sequential! |
||
Chapter |
19 |
- ASP.NET Web Applications |
enum EmpType |
||
Chapter |
20 |
- XML Web Services |
{ |
Manager = 10, |
|
Index |
List of Figures
Grunt = 1,
List of TablesContractor = 100,
VP = 9
}
Under the hood, the storage type used for each item in an enumeration automatically maps to a System.Int32 by default. You are also free to change this to your liking. For example, if you want to set the underlying storage value of EmpType to be a byte rather than an int, you would write the following:
// This time, EmpType maps to an underlying byte.
enum EmpType : byte
{
Manager = 10,
Grunt = 1,
Contractor = 100,
VP = 9
}
C# and the .NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
Note C# enumerationsThis comprehensivecan be definedtext startsin awithsimilara briefmannerov rviewfor anyof theof the core numerical types (byte, sbyte, short,C# languageushort,aint,d uint,then long,quicklyormovesulong)to. key technical and
architectural issues for .NET developers.
Once you have established the range and storage type of your enumeration, you can use them in place of so-called "magic numbers." Assume you have a class defining a static public function, taking EmpType as
Table of Contents the sole parameter:
C# and the .NET Platform, Second Edition
Introduction
using System;
Part One - Introducing C# and the .NET Platform
class EnumClass
Chapter 1 |
- The Philosophy of .NET |
|
|
|
{ |
|
|
|
|
Chapter 2 |
- Building C# Applications |
|
|
|
public static void AskForBonus(EmpType e) |
||||
Part Two{- The C# Programming Language |
|
|
||
Chapter 3 |
- C# Language Fundamentals |
|
|
|
|
switch(e) |
|
|
|
Chapter 4 |
- Object-Oriented Programming with C# |
|
||
|
{ |
|
: |
|
Chapter 5 |
- ExcaseeptionsEmpTypeand Object.ContractorLifetime |
|
||
Chapter 6 |
- InterfacesConsolea d Collections.WriteLine("You already get enough cash..."); |
|||
Chapter 7 |
- Callbackbreak;Interfaces, Delegates, and Events |
|
||
Chapter 8 |
- Advancedcase EmpType.GruntC# Type Construction: Techniques |
|||
Part Three - ProgrammingConsole.WriteLine("Youwith .NET Assemblies |
have got to be kidding..."); |
|||
Chapter 9 |
- Understandingbreak; |
.NET Assemblies |
|
|
Chapter 10 |
- Processes,case EmpType.ManagerAppDomains, Contexts,: and Threads |
|||
Chapter 11 |
- Type Reflection,Console.WriteLine("HowLate Binding, and Attributeabout-Based Programmingstock options instead?"); |
break;
Part Four - Leveraging the .NET Libraries
case EmpType.VP:
Chapter 12 - Object Serialization and the .NET Remoting Layer
Console.WriteLine("VERY GOOD, Sir!");
Chapter 13 - Building a Better Window (Introducing Windows Forms) break;
Chapter 14 - A Better Painting Framework (GDI+) default: break;
Chapter 15 - Programming with Windows Forms Controls
}
Chapter 16 - The System.IO Namespace
}
Chapter 17 - Data Access with ADO.NET
public static int Main(string[] args)
Part Five{- Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
// Make a contractor type.
Chapter 19 - ASP.NET Web Applications
EmpType fred;
Chapter 20 - XMLfredWeb=ServicesEmpType.Contractor;
Index AskForBonus(fred);
List of Figures return 0;
}
List of Tables
}
The System.Enum Base Class
The interesting thing about C# enumerations is that they implicitly derive from System.Enum. This base class defines a number of methods that allow you to interrogate and transform a given enumeration. Table 3-13 documents some items of interest, all of which are static.
Table 3-13: Select static Members of System.Enum
|
Member of |
C# and the |
.NETMeaningPlatform,in LifeSecond Edition |
|
|
System.Enumby Andrew |
Troelsen |
ISBN:1590590554 |
|
|
|
|
|
|
|
Format() |
Apress © 2003 |
(1200 pages) |
|
|
|
This method converts a value of a specified enumerated type to its |
||
|
|
This comprehensive text starts with a brief overview of the |
||
|
|
|
equivalent string representation according to the specified format. |
|
|
|
C# language |
and then quickly moves to key technical and |
|
|
GetName() |
architectural |
issues for .NET developers. |
|
|
|
Retrieves the name (or array of names) for the constant in the |
||
|
GetNames() |
|
specified enumeration that has the specified value. |
|
|
|
|
|
|
Table of Contents |
|
Returns the underlying type of the specified enumeration. |
||
|
GetUnderlyingType() |
|||
C# and the .NET Platform, Second Edition |
|
Retrieves an array of the values of the constants in a specified
enumeration.
Part One - Introducing C# and the .NET Platform
|
Chapter 1 - The Philosophy of |
|
|
.NET |
|
|
||
|
|
IsDefined() |
|
|
Returns an indication whether a constant with a specified value exists |
|
|
|
|
Chapter 2 |
- Building C# Applications |
|
|
||||
|
|
|
|
|
|
in a specified enumeration. |
|
|
Part Two - The C# Programming |
|
|
Language |
|
|
|||
|
|
|||||||
|
|
Parse() |
|
|
|
Converts the string representation of the name or numeric value of |
|
|
Chapter 3 |
- C# Language |
|
Fundamentals |
|
|
|||
Chapter 4 |
- Object-Oriented |
|
|
one or more enumerated constants to an equivalent enumerated |
|
|
||
|
Programming with C# |
|
|
|||||
|
|
|
|
|
|
object. |
|
|
|
|
Chapter 5 |
- Exceptions and |
|
Object Lifetime |
|
|
|
Chapter 6 |
- Interfaces and Collections |
First, System.Enum defines a static method named GetUnderlyingType(), which resolves (pardon the
Chapter 7 - Callback Interfaces, Delegates, and Events
redundancy) the underlying data type used to represent a given enumeration:
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
// Get underlying type (System.Byte for the current example).
Chapter 9 - Understanding .NET Assemblies
Console.WriteLine(Enum.GetUnderlyingType(typeof(EmpType)));
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Of greater interest is the ability to extract the named constant behind the numerical values. How many
Chapter 12 - Object Serialization and the .NET Remoting Layer
times have you had to perform transformational logic between a C++ enumeration and the underlying
Chapter 13 - Building a Better Window (Introducing Windows Forms)
string value? Using the inherited ToString() method, the dirty work as been done on your behalf:
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
// Print out string version of 'fred'.
Chapter 16 - The System.IO Namespace
Console.WriteLine(fred.ToString());
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
ChapterIf you require18 - ASPa more.NET WebexoticPagesformatandofWebyourControlsenumerations, you can make use of the static Enum.Format() Chaptermethod19. For- ASPexample,.NET WebusingApplicationsthe EmpType variable, you may extract the corresponding string, by
specifying "G" as a parameter to Enum.Format(). You may also specify the hexadecimal value (x) or
Chapter 20 - XML Web Services
decimal value (d) of the underlying enum. System.Enum also defines a static method named GetValues().
Index
This method returns an instance of System.Array, with each item in the array corresponding to a member
List of Figures
of the specified enumeration. To illustrate these points, ponder the following:
List of Tables
// Get all statistics for the EmpType enumeration.
Array obj = Enum.GetValues(typeof(EmpType));
Console.WriteLine("This enum has {0} members.", obj.Length);
// Now show the string name and associated value.
foreach(EmpType e in obj)
{
Console.Write("String name: {0},", e.ToString());
Console.Write(" int: ({0}),", Enum.Format(typeof(EmpType), e, "D")); Console.Write(" hex: ({0})\n", Enum.Format(typeof(EmpType), e, "X"));
}
As you can guess, this code block prints out the name/value pairs (in decimal and hexadecimal) for the
EmpType enumeration.
Next, let's explore the IsDefined property. This allows you to determine if a given string name is a member
C# and the .NET Platform, Second Edition
of the current enumeration. For example, assume you wish to know if the value "SalesPerson" is part of
by Andrew Troelsen ISBN:1590590554 the EmpType enumeration:
Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
// Does EmpType have a SalePerson value?
C# language and then quickly moves to key technical and
if(Enum.IsDefined(typeof(EmpType), "SalesPerson")) architectural issues for .NET developers.
Console.WriteLine("Yep, we have sales people.");
else
Table of Consoletents.WriteLine("No, we have no profits...");
C# and the .NET Platform, Second Edition
Introduction
It is also possible to generate an enumeration from a string literal via the static Enum.Parse() method. Given that Parse() returns a generic System.Object, you will need to cast the return value into the correct
enum type (more on casting in the next chapter):
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
// Prints: "Sally is a Manager"
Chapter 3 - C# Language Fundamentals
EmpType sally = (EmpType)Enum.Parse(typeof(EmpType), "Manager");
Chapter 4 - Object-Oriented Programming with C#
Console.WriteLine("Sally is a {0}", sally.ToString());
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
As you might guess, this could be extremely helpful when you are prompting for user input, and wish to ParttranslateThree the- Programmingtextual datawithinto an.NETenumerationAssemblies type for use in the program.
Chapter 9 - Understanding .NET Assemblies
Last but not least, it is worth pointing out that C# enumerations support the use of various overloaded
Chapter 10 - Processes, AppDomains, Contexts, and Threads
operators, which test against the assigned values. For example:
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter// Which12 - Objectof theseSerializatitwonEmpTypeand the .NETvariablesRemoting Layerhas the greatest numerical value?
EmpType Joe = EmpType.VP;
Chapter 13 - Building a Better Window (Introducing Windows Forms)
EmpType Fran = EmpType.Grunt;
Chapter 14 - A Better Painting Framework (GDI+)
if(Joe < Fran)
Chapter 15 - Programming with Windows Forms Controls
Console.WriteLine("Joe's value is less than Fran's");
Chapter 16 - The System.IO Namespace
else
Chapter 17 - Data Access with ADO.NET
Console.WriteLine("Fran's value is less than Joe'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
SOURCE The EnumExample project is located under the Chapter 3 subdirectory.
IndexCODE
List of Figures
List of Tables
Defining StructuresC# and the .NETin Platform,C# Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
While you have already encountered structures earlier in this chapter, they do deserve a second look.
Apress © 2003 (1200 pages)
Structures in general are a way to achieve the bare bones benefits of object orientation (i.e.,
This comprehensive text starts with a brief overview of the
encapsulation) whileC# languagehaving theandefficiencythen quicklyof stackmoves-allocatedto key technicaldata. Beyondand this key point, C# structures behave very mucharchitecturallike a customissuesclassfor. .NET developers.
Note Over the course of this chapter you may have noticed that I have defined all structures in capital
Table of Contentsletters. This is in no way a requirement, but is simply an old C style naming convention I can't C# and theseem.NET Platform,to get ridSecondof. As youEditionexplore the .NET base class libraries, you will not find structures Introductiondefined in all caps.
Part One - Introducing C# and the .NET Platform
As mentioned, structures can take constructors (provided they have arguments), can implement interfaces, and can contain numerous members. Furthermore, recall that C# structures do not have an identically named alias in the .NET library (that is, there is no System.Structure class), but are implicitly
derived from System.ValueType to retrofit the virtual members of System.Object to work with value-based
Chapter 3 - C# Language Fundamentals semantics. Here is a simple example:
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
Manager = 10, Grunt = 1,
Part Three - Programming with .NET Assemblies
Contractor = 100, VP = 9
Chapter 9 - Understanding .NET Assemblies
}
Chapter 10 - Processes, AppDomains, Contexts, and Threads
struct EMPLOYEE
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
{
Part Four - Leveraging the .NET Libraries
public EmpType title; // One of the fields is our custom enum.
Chapter 12 - Object Serialization and the .NET Remoting Layer public string name;
Chapter public13 - Buildingshorta BetterdeptID;Window (Introducing Windows Forms)
Chapter} 14 - A Better Painting Framework (GDI+)
Chapterclass15StructTester- 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
// Create and format Fred.
Chapter 18 - ASP.NET Web Pages and Web Controls
EMPLOYEE fred;
Chapter 19 - ASP.NET Web Applications
fred.deptID = 40;
Chapter 20 - XML Web Services
fred.name = "Fred";
Index
fred.title = EmpType.Grunt;
List of Figures
return 0;
List of Tables
}
}
Here, you created an EMPLOYEE structure on the stack and manipulated each field using the dot operator. To be sure, if you do not denote a custom constructor, you are required to assign values to each field before making use of your stack-based variable.
To provide a more optimized construction of this type, you are free to define additional custom constructors. Recall that you cannot redefine the default constructor for a C# structure, as this is a reserved member. Given this fact, any custom constructors must take some number of parameters:
// Structs may define custom constructors (if they have args).
struct EMPLOYEE
{
// Fields.
public EmpType title;
|
C# and the .NET Platform, Second Edition |
||
public string name; |
ISBN:1590590554 |
||
|
by Andrew Troelsen |
||
public short deptID; |
|
||
|
Apress © 2003 (1200 pages) |
|
|
// Constructor. |
|
|
|
|
This comprehensive text s arts with a brief overview of the |
||
public EMPLOYEE(EmpType et, |
string n, short d) |
||
{ |
C# language and then quickly moves to key technical and |
||
architectural issues for .NET developers. |
|||
|
title = et; |
|
|
|
name = n; |
|
|
Table of ContentsdeptID = d; |
|
|
|
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 |
|
|
With this, you can create a new employee as follows: |
|||
Part Two - The C# Programming Language |
|
||
Chapter 3 |
- C# Language Fundamentals |
|
|
class StructTester |
|
|
|
Chapter 4 |
- Object-Oriented Programming with C# |
||
{ |
|
|
|
Chapter 5 |
- Exceptions and Object Lifetime |
|
|
public static int Main(string[] args) |
|||
Chapter 6 |
- Interfaces and Collections |
|
|
{ |
|
|
|
Chapter 7 |
- Callback In erfac |
s, Delegates, and Events |
|
|
// Must use |
'new' to trigger a custom constructor. |
|
Chapter 8 |
- Advanced C# Type Construction Techniques |
||
|
EMPLOYEE mary = new EMPLOYEE(EmpType.VP, "Mary", 10); |
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
Note Remember! The "new" keyword is only used for consistency between value-based and
Chapter 13 - Building a Better Window (Introducing Windows Forms)
reference-based types. When you "new" a structure, you are still creating a stack-based entity.
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Contrtols
Structures can, of course, be used as parameters any member function. For example, assume the ChapterStructTester16 - TheclassSystdefinesm.IO Namespacemethod named DisplayEmpStats():
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
// Extract interesting information from an EMPLOYEE structure.
Chapter 18 - ASP.NET Web Pages and Web ControlsEMPLOYEE e public static void DisplayEmpStats( )
Chapter 19 - ASP.NET Web Applications
{
Chapter 20 - XML Web Services
Console.WriteLine("Here is {0}\'s info:", e.name);
Index Console.WriteLine("Department ID: {0} ", e.deptID);
List of FiguresConsole.WriteLine("Title: {0} ", e.title);
List} of Tables
Here is a test run of using DisplayEmpStats():
// Let Mary & Fred strut their stuff.
public static int Main(string[] args)
{
...
DisplayEmpStats(mary);
DisplayEmpStats(fred); return 0;
}
(Un)boxing Custom Structures
As mentioned earlierC# aindthisthechapter,.NET Platform,boxing andSecondunboxingEditionprovide a convenient way to flip between value types and referenceby Andrewtypes. AsTroelsenyou recall, to convert a structureISBN:1590590554variable into an object reference, simply
box the value: Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and
// Create and box a new employee.
architectural issues for .NET developers.
EMPLOYEE stan = new EMPLOYEE(EmpType.Grunt, "Stan", 10);
object stanInBox = stan;
Table of Contents
C# and the .NET Platform, Second Edition
Because stanInBox is a reference-based data type (which still holds the internal values of the original
Introduction
EMPLOYEE data type) you can unbox the reference as needed to gain access to the members of the
Part One - Introducing C# and the .NET Platform
EMPLOYEE structure:
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
// Because we have boxed our value data type into a structure,
Part Two - The C# Programming Language
// we can unbox and manipulate the contents.
Chapter 3 - C# Language Fundamentals
public static void UnboxThisEmployee(object o)
Chapter 4 - Object-Oriented Programming with C#
{
Chapter 5 - Exceptions and Object Lifetime
EMPLOYEE temp = (EMPLOYEE)o;
Chapter 6 - InterfacesWriteLine(tempand Collec ions
Console. .name + " is alive!");
Chapter} 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Here is the calling logic and output: |
||
Chapter 9 |
- Understanding .NET Assemblies |
|
Chapter 10 |
- Processes, AppDomains, Contexts, and Threads |
|
Chapter// Send11 |
-boxedType Reflection,employeeLateinBinding,for andprocessing.Attribute-Based Programming |
|
PartUnboxThisEmployee(stanInBox);Four - Leveraging the .NET Libraries |
||
Chapter 12 |
- Object Serialization and the .NET Remoting Layer |
|
Chapter 13 |
- Building a Better Window (Introducing Windows Forms) |
|
Recall that the C# compiler automatically box values where appropriate. Therefore, it would be |
||
Chapter 14 |
- A Better Painting Framework (GDI+) |
|
permissible to directly pass stan (the EMPLOYEE type) into UnboxThisEmployee() directly: |
||
Chapter 15 |
- Programming with Windows Forms Controls |
|
Chapter 16 |
- The System.IO Namespace |
|
Chapter// Stan17 |
-isDataboxedAccessautomatically.with ADO.NET |
|
PartUnboxThisEmployee(stan);Five - Web Applications and XML Web Services |
||
Chapter 18 |
- ASP.NET Web Pages and Web Controls |
|
Chapter 19 |
- ASP.NET Web Applications |
|
However, because you have defined UnboxThisEmployee() to take an object parameter, you have no |
||
Chapter 20 |
- XML Web Servic s |
|
choice but to unbox this reference to access the fields of the EMPLOYEE structure. |
||
Index |
|
|
List ofSOURCEFigures |
The Structures project is located under the Chapter 3 subdirectory. |
|
CODE |
|
|
List of Tables |
|
Defining CustomC# and theNamespaces.NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
To this point, you have been building small test programs leveraging existing namespaces in the .NET
Apress © 2003 (1200 pages)
universe (System in particular). When you build real-life applications, it can be very helpful to group your
This comprehensive text starts with a brief overview of the
related types intoC#customlanguagenamespacesand then .quicklyIn C#,movesthis is accomplishedto key technicalusingand the "namespace" keyword.
architectural issues for .NET developers.
Assume you are developing a collection of geometric classes named Square, Circle, and Hexagon. Given their similarities, you would like to group them all together into a shared custom namespace. You have two
TablebasicofapproachesContents . First, you may choose to define each class within a single file (shapeslib.cs) as follows:
C# and the .NET Platform, Second Edition
Introduction
// shapeslib.cs
PartusingOne -System;Introducing C# and the .NET Platform
Chnamespacept r 1 - TheMyShapesPhilosophy of .NET
Chapter{ 2 - Building C# Applications
Part Two//- TheCircleC# Programmingclass. Language
Chapter public3 - C# Languageclass Circle{Fundamentals// Interesting methods... }
// Hexagon class.
Chapter 4 - Object-Oriented Programming with C#
public class Hexagon{ // More interesting methods... }
Chapter 5 - Exceptions and Object Lifetime
// Square class.
Chapter 6 - Interfaces and Collections
public class Square{ // Even more interesting methods... }
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
Notice how the MyShapes namespace acts as the conceptual "container" of each type. Alternatively, you
Chapter 10 - Processes, AppDomains, Contexts, and Threads
can split a single namespace into multiple C# files. To do so, simply wrap the given class definitions in the
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming same namespace:
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
// circle.cs
Chapter 13 - Building a Better Window (Introducing Windows Forms)
using System;
Chapter 14 - A Better Painting Framework (GDI+)
namespace MyShapes
Chapter 15 - Programming with Windows Forms Controls
{
Chapter 16 - The System.IO Namespace
// Circle class.
Chapter 17 - Data Access with ADO.NET
class Circle{ // Interesting methods... }
Part} Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter// hexagon19 - ASP.cs.NET Web Applications
Chapterusing20System;- XML Web Services
namespace MyShapes
Index
{
List of Figures
// Hexagon class.
List of Tables
class Hexagon{ // More interesting methods... }
}
// square.cs
using System; namespace MyShapes
{
// Square class.
class Square{ // Even more interesting methods... }
}
As you already know, when another application you are building wishes to use these fine objects from within its namespace, simply use the "using" keyword:
// Make use of objects defined in another namespace
C# and the .NET Platform, Second Edition using System;
by Andrew Troelsen |
ISBN:1590590554 |
using MyShapes; |
|
Apress © 2003 (1200 pages) |
|
namespace MyApp |
|
{This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and class ShapeTester
architectural issues for .NET developers.
{
public static void Main()
{
Table of Contents
// All defined in the MyShapes namespace.
C# and the .NET Platform, Second Edition
Hexagon h = new Hexagon();
Introduction
Circle c = new Circle();
Part One - Introducing C# and the .NET Platform
Square s = new Square();
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
Resolving Name Clashes Across Namespaces
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
A namespace can also be used to avoid nasty name clashes across multiple namespaces. Assume the
Chapter 8 - Advanced C# Type Construction Techniques
ShapeTester class wishes to make use of a new namespace termed My3DShapes, which defines three
Part Three - Programming with .NET Assemblies
additional classes capable of rendering a shape in stunning 3D:
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
// Another shapes namespace...
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
using System;
Part Four - Leveraging the .NET Libraries
namespaceMy3DShapes
Chapter 12 - Object Serialization and the .NET Remoting Layer
{
Chapter 13 - Building a Better Window (Introducing Windows Forms)
// 3D Circle class.
Chapter 14 - A Better Painting Framework (GDI+)
class Circle{ }
Chapter 15 - Programming with Windows Forms Controls
// 3D Hexagon class
Chapter class16 - TheHexagon{System.IO Namespace}
Chapter //17 -3DDataSquareAccess withclassADO.NET
Part Fiveclass- Web ApplicationsSquare{ }and XML Web Services
Chapter} 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
If you update ShapeTester as was done here, you are issued a number of compiletime errors, because
Index
both namespaces define identically named types:
List of Figures
List of Tables
// Ambiguities abound!
using System;
using MyShapes;
using My3DShapes;
namespace MyApp
{
class ShapeTester
{
public static void Main()
{
// Which namespace do I reference?
Hexagon h = new Hexagon(); |
// Compiler error! |
||||||
Circle |
c |
= |
new |
Circle(); |
// |
Compiler |
error! |
Square |
s |
= |
new |
Square(); |
// |
Compiler |
error! |
}
}
} |
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 |
||
|
C# language and then q |
ickly moves to key technical and |
As one would hope, these errors are caught at compile time. Resolving the ambiguity is simply a matter of
architectural issues for .NET developers. using "fully qualified names:"
// We have now resolved the ambiguity.
Table of Contents
public static void Main()
C# and the .NET Platform, Second Edition
{
Introduction
My3DShapes.Hexagon h = new My3DShapes.Hexagon();
Part One - Introducing C# and the .NET Platform
My3DShapes.Circle c = new My3DShapes.Circle();
Chapter 1 - The Philosophy of .NET
MyShapes.Square s = new MyShapes.Square();
Chapter 2 - Building C# Applications
}
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Defining Namespace Aliases
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
An alternative approach to resolving namespace ambiguity is accomplished through the use of aliases.
Chapter 7 - Callback Interfaces, Delegates, and Events
For example:
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
using System;
Chapter 9 - Understanding .NET Assemblies using MyShapes;
Chapter 10 - Processes, AppDomains, Contexts, and Threads using My3DShapes;
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Make an alias to a class defined in another namespace.
Part Four - Leveraging the .NET Libraries
using The3DHexagon = My3DShapes.Hexagon;
Chapter 12 - Object Serialization and the .NET Remoting Layer namespace MyApp
Chapter 13 - Building a Better Window (Introducing Windows Forms)
{
Chapter 14 - A Better Painting Framework (GDI+)
class ShapeTester
Chapter{15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
public static void Main()
Chapter 17 -{Data Access with ADO.NET
Part Five - Web ApplicationsMy3DShapesand XML.HexagonWeb Servicesh = new My3DShapes.Hexagon();
Chapter 18 - ASP.NETMy3DShapWeb P ges.andCircleWeb Controlsc = new My3DShapes.Circle();
Chapter 19 - ASP.NETMyShapesWeb Applications.Square s = new MyShapes.Square();
// Create a 3D hex using a defined alias:
Chapter 20 - XML Web Se vices
Index |
The3DHexagon h2 = new The3DHexagon(); |
List of Figures} |
|
List of Tables} |
|
} |
|
Nested Namespaces
When organizing your types, you are free to nest namespaces within other namespaces. The .NET base class libraries do so in numerous places to provide an even deeper level of type organization. For example, if you wish to create a higher-level namespace that contains the existing My3DShapes namespace, you can update your code as follows:
// The Chapter3Types.My3DShapes namespace contains 3 classes.
using System;
namespace Chapter3Types
{
namespace My3DShapes
{ |
C# and the .NET Platform, Second Edition |
|
|
|
// 3D |
Circle class. |
ISBN:1590590554 |
|
by Andrew Troelsen |
||
|
class |
Circle{ } |
|
|
Apress © 2003 (1200 pages) |
|
|
|
// 3D |
Hexagon class |
|
|
This comprehensive text starts with a brief overview of the |
||
|
class |
Hexagon{ } |
|
|
C# language and then quickly moves to key technical and |
||
|
// 3D |
Square class |
|
|
architectural issues for .NET developers. |
|
|
|
class |
Square{ } |
|
}
}
Table of Contents
C# and the .NET Platform, Second Edition
Introduction
Do note that you are also able to define a nested namespace using the following shorthand (which as you
Part One - Introducing C# and the .NET Platform
may guess, helps decrease the use of the moving horizontal scrollbar within the VS .NET code window):
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
// The Chapter3Types.My3DShapes namespace contains 3 classes.
Part Two - The C# Programming Language
using System;
Chapter 3 - C# Language Fundamentals
namespaceChapter3Types.My3DShapes
Chapter 4 - Object-Oriented Programming with C#
{
Chapter 5 - Exceptions and Object Lifetime
// 3D Circle class.
Chapter 6 - Interfaces and Collections
class Circle{ }
Chapter 7 - Callback Interfaceclass, Delegates, and Events
// 3D Hexagon
Chapterclass8 - AdvancedHexagon{C# Type} Construction Techniques
Part Three// -3DProgrammingSquare classwith .NET Assemblies
Chapterclass9 - UnderstandingSquare{ }.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
ChaptTher"Default12 - Object SeriNamespace"lization and the .NETofRemotingVS .NETLayerIDE
Chapter 13 - Building a Better Window (Introducing Windows Forms)
ChapterOn a final14 -namespaceA B tter Painting-relatedFrameworknote, it is(GDI+)worth pointing out that by default, when you create a new C# Chapterproject15using- ProgrammingVS .NET, thewithnameWindowsof theFormstopmostControlsnamespace in your application will be identical to that of
the name you gave your initial project. As you have seen, as you insert new types into your project using
Chapter 16 - The System.IO Namespace
the various IDE Wizards, they will automatically be wrapped within this default namespace. If you wish to
Chapter 17 - Data Access with ADO.NET
change the name of this default namespace after the fact, simply access the Default Namespace option
Part Five - Web Applications and XML Web Services
of the project's Properties dialog (Figure 3-21).
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Chapter
Index
List of
List of
Figure 3-21: Configuring the default namespace
With this update, any new item inserted into the project will be wrapped within the Intertech.MyNamespaces namespace (and obviously, if another namespace wishes to use these types,
the correct using directive must be applied).
C# and the .NET Platform, Second Edition
SOURCE by AndrewThe NamespacesTroelsen project is located underISBN:1590590554the Chapter 3 subdirectory.
CODE 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