- •Contents
- •What Is C#?
- •C# Versus Other Programming Languages
- •Preparing to Program
- •The Program Development Cycle
- •Your First C# Program
- •Types of C# Programs
- •Summary
- •Workshop
- •C# Applications
- •Basic Parts of a C# Application
- •Structure of a C# Application
- •Analysis of Listing 2.1
- •Object-Oriented Programming (OOP)
- •Displaying Basic Information
- •Summary
- •Workshop
- •Variables
- •Using Variables
- •Understanding Your Computer’s Memory
- •C# Data Types
- •Numeric Variable Types
- •Literals Versus Variables
- •Constants
- •Reference Types
- •Summary
- •Workshop
- •Types of Operators
- •Punctuators
- •The Basic Assignment Operator
- •Mathematical/Arithmetic Operators
- •Relational Operators
- •Logical Bitwise Operators
- •Type Operators
- •The sizeof Operator
- •The Conditional Operator
- •Understanding Operator Precedence
- •Converting Data Types
- •Understanding Operator Promotion
- •For Those Brave Enough
- •Summary
- •Workshop
- •Controlling Program Flow
- •Using Selection Statements
- •Using Iteration Statements
- •Using goto
- •Nesting Flow
- •Summary
- •Workshop
- •Introduction
- •Abstraction and Encapsulation
- •An Interactive Hello World! Program
- •Basic Elements of Hello.cs
- •A Few Fundamental Observations
- •Summary
- •Review Questions
- •Programming Exercises
- •Introduction
- •Essential Elements of SimpleCalculator.cs
- •A Closer Look at SimpleCalculator.cs
- •Simplifying Your Code with Methods
- •Summary
- •Review Questions
- •Programming Exercises
- •Introduction
- •Lexical Structure
- •Some Thoughts on Elevator Simulations
- •Concepts, Goals and Solutions in an Elevator Simulation Program: Collecting Valuable Statistics for Evaluating an Elevator System
- •A Deeper Analysis of SimpleElevatorSimulation.cs
- •Class Relationships and UML
- •Summary
- •Review Questions
- •Programming Exercises
- •The Hello Windows Forms Application
- •Creating and Using an Event Handler
- •Defining the Border Style of the Form
- •Adding a Menu
- •Adding a Menu Shortcut
- •Handling Events from Menus
- •Dialogs
- •Creating Dialogs
- •Using Controls
- •Data Binding Strategies
- •Data Binding Sources
- •Simple Binding
- •Simple Binding to a DataSet
- •Complex Binding of Controls to Data
- •Binding Controls to Databases Using ADO.NET
- •Creating a Database Viewer with Visual Studio and ADO.NET
- •Resources in .NET
- •Localization Nuts and Bolts
- •.NET Resource Management Classes
- •Creating Text Resources
- •Using Visual Studio.NET for Internationalization
- •Image Resources
- •Using Image Lists
- •Programmatic Access to Resources
- •Reading and Writing RESX XML Files
- •The Basic Principles of GDI+
- •The Graphics Object
- •Graphics Coordinates
- •Drawing Lines and Simple Shapes
- •Using Gradient Pens and Brushes
- •Textured Pens and Brushes
- •Tidying up Your Lines with Endcaps
- •Curves and Paths
- •The GraphicsPath Object
- •Clipping with Paths and Regions
- •Transformations
- •Alpha Blending
- •Alpha Blending of Images
- •Other Color Space Manipulations
- •Using the Properties and Property Attributes
- •Demonstration Application: FormPaint.exe
- •Why Use Web Services?
- •Implementing Your First Web Service
- •Testing the Web Service
- •Implementing the Web Service Client
- •Understanding How Web Services Work
- •Summary
- •Workshop
- •How Do Web References Work?
- •What Is UDDI?
- •Summary
- •Workshop
- •Passing Parameters and Web Services
- •Accessing Data with Web Services
- •Summary
- •Workshop
- •Managing State in Web Services
- •Dealing with Slow Services
- •Workshop
- •Creating New Threads
- •Synchronization
- •Summary
- •The String Class
- •The StringBuilder Class
- •String Formatting
- •Regular Expressions
- •Summary
- •Discovering Program Information
- •Dynamically Activating Code
- •Reflection.Emit
- •Summary
- •Simple Debugging
- •Conditional Debugging
- •Runtime Tracing
- •Making Assertions
- •Summary
540
Extreme C#
PART IV
Console.WriteLine( “myStringBuilder[1]: {0}”, charResult);
The return value in this case is ‘y’.
String Formatting
When performing a Console.WriteLine() method call, any format strings default to string type unless special formatting is applied. Often it’s necessary to perform more sophisticated formatting on various types such as numbers, strings, and dates.
Numeric Formatting
C# has several formatting characters for numeric formatting. Table 25.1 shows the C# number format specifiers.
TABLE 25.1 Numeric Format Specifiers
Format Character |
Description |
C or c |
Currency |
D or d |
Decimal |
E or e |
Scientific/exponential |
F or f |
Fixed point |
G or g |
General (can be E or F format) |
N or n |
Number |
R or r |
Roundtrip (convertible to string and back) |
X or x |
Hexadecimal |
|
|
The following example shows how to use numeric formatting:
Console.WriteLine(“Hex: {0:x}”, 255);
This example converts the integer 255 to hexadecimal notation. The result is hex ff. The value is in lowercase because a lowercase format character was used. Results are in uppercase when uppercase format characters are used.
String Manipulation
CHAPTER 25
541
Picture Formatting
It’s often necessary to have more control over the format of output beyond default formatting or a simple numeric formatting character. In these cases, picture formatting will help present output exactly as desired. Table 25.2 shows the picture formatting characters.
TABLE 25.2 Picture Format Characters
Format Character |
Description |
0 |
Zero placeholder |
# |
Display digit placeholder |
. |
Decimal point |
, |
Group separator/multiplier |
% |
Percent |
E+0, E-0, e+0, e-0 |
Exponent notation |
\ |
Literal character |
‘ABC’ or “ABC” |
Literal string |
; |
Section separator |
|
|
The following example shows how to use picture formatting:
Console.WriteLine(“Million: {0:$#,#.00}”, 1000000);
This example formats the number to make it appear as currency. (The C number format character could have been used, but it wouldn’t have served the purpose of this example.) The result of this formatting produces “$1,000,000.00”. The $ sign is placed into the output at the position it appears. The # symbol holds a place for a number before and after the comma. The ‘,’ character causes a comma to be placed between every three digits of the output. The decimal point will be placed to the right of the whole number. To get the cents portion to appear, two zeros are put after the decimal point in the format specifier. Had these been # symbols, nothing would have appeared after the decimal point.
Regular Expressions
Regular expressions provide the capability to manipulate and search text efficiently. The System.Text.RegularExpressions namespace contains a set of classes that enable regular expression operations in C# programs. Listing 25.1 shows the code for a program similar to grep (Global Regular Expression Print) expressions:
25
TRINGS
ANIPULATIONM
542
Extreme C#
PART IV
LISTING 25.1 Regular Expressions
using System;
using System.Text.RegularExpressions; using System.IO;
class lrep
{
static int Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine(“Wrong number of args!”); return 1;
}
Regex re = new Regex(args[0]);
StreamReader sr = new StreamReader(args[1]);
string nextLine = sr.ReadLine();
while (nextLine != null)
{
Match myMatch = re.Match(nextLine);
if (myMatch.Success)
{
Console.WriteLine(“{0}: {1}”, args[1], nextLine);
}
nextLine = sr.ReadLine();
}
sr.Close();
return 0;
}
}
Note
Global Regular Expression Print (grep), written by Doug McIlroy, is a popular Unix utility. It allows you to perform a command line search for regular expressions within the text of one or more files.
String Manipulation
CHAPTER 25
543
The Listing 25.1 program is called lrep, which stands for Limited Regular Expression Print. It may be limited in features, but because of the built-in regular expression classes, it’s very powerful. Here’s an example of how to use it:
lrep string lrep.cs
The first parameter, lrep, is the command name of the program. The second parameter, string, is the regular expression. It happens to be a normal string without anything special, but can also take the same set of regular expressions as the Perl programming language. The third parameter, lrep.cs, is the filename to search for the regular expression. Here’s the output:
lrep.cs: |
static int |
Main(string[] args) |
lrep.cs: |
string |
nextLine = sr.ReadLine(); |
Each line of output contains the name of the file that was searched. Following that is the text of the line where the regular expression matched. The next example shows how the regular expression is set in the program:
Regex re = new Regex(args[0]);
A regular expression is created by instantiating a Regex object. The following example shows one way to use a regular expression object:
Match myMatch = re.Match(nextLine);
The Match() method of the Regex class is used to determine if a given string contains text that matches a regular expression. This program opens a file, specified in the command line arguments, and reads each line to see if there is a match. By using the Success property of the match object, the program can figure out that a match was made. This program writes the positive matching lines to the console, as shown in the output lines.
This program used a late bound matching scheme to achieve its goals. However, a regular expression may be initialized with constants, increasing efficiency through compile time optimization.
Summary
There is a plethora of options available in the way of string manipulation with the system libraries. The String class provides basic string handling but has many methods available for returning new strings with various modifications.
For sophisticated string manipulation, use the StringBuilder class. It allows modification of the string in the same object without the overhead of creating a new object with each operation.
25
TRINGS
ANIPULATIONM
544
Extreme C#
PART IV
Strings need to be formatted for many processing activities. There are simple number formatting options as well as picture formatting.
A welcome feature of the system libraries is regular expressions. Regular expressions allow powerful string manipulation that is more efficient than either String or StringBuilder class operations.
Strings and StringBuilders have various features that make them work well as collection objects. The next chapter, “C# Collections,” explains why this is true and provides insight to help understand the internal mechanism of collections.
CHAPTER 28
Reflection
IN THIS CHAPTER
• Discovering Program Information 582
• Dynamically Activating Code 588
• Reflection.Emit 590