- •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
Working with Operators |
81 |
3 – 2
100.4 – 92348.67
You will find that most of the operators fall into the binary operator type.
Ternary Operator Types
Ternary operators are the most complex operator types to work with. As the name implies, this type of operator works on three variables. C# has only one true ternary operator, the conditional operator. You will learn about it later today. For now, know that ternary operators work with three variables.
Punctuators
Before jumping into the different categories and the specific operators within C#, it is important to understand about punctuators. Punctuators are a special form of operator that helps you format your code, do multiple operations at once, and simply signal information to the compiler. The punctuators that you need to know about are
• Semicolon :. The primary use of the semicolon is to end each C# statement. A |
4 |
|
semicolon is also used with a couple of the C# statements that control program |
||
|
||
flow. You will learn about the use of the semicolon with the control statements on |
|
|
Day 5,”Control Statements.” |
|
•Comma ,. The comma is used to stack multiple commands on the same line. You saw the comma in use on Day 3, “Storing Information with Variables,” in a number of the examples. The most common time to use the comma is when declaring multiple variables of the same type:
int var1, var2, var3;
•Parentheses (). Parentheses are used in multiple places. You will see later in today’s lesson, that you can use parentheses to force the order of execution. Additionally, parentheses are used with functions.
•Braces {}. Braces are used to group pieces of code. You have seen braces used to encompass classes in many of the examples. You should also have noticed that braces are always used in pairs.
Punctuators operate the same way punctuation within a sentence operates. For example, you end a sentence with a period or another form of punctuation. In C#, you end a “line” of code with a semicolon or other punctuator. Line is in quotation marks because a line of code might actually take up multiple lines in a source listing. As you learned on Day 2, “Understanding C# Programs,” whitespace and newlines are ignored.
82 |
Day 4 |
Note
You will find that you can also use braces within the routines you create to block off code. The code put between two braces, along with the braces, is called a block.
The Basic Assignment Operator
The first operator that you need to know about is the basic assignment operator. which is an equal sign (=). You’ve seen this operator already in a number of the examples in earlier lessons.
The basic assignment operator is used to assign values. For example, to assign the value 142 to the variable x, you type
x = 142;
This compiler takes the value that is on the right side of the assignment operator and places it in the variable on the left side. Consider the following:
x = y = 123;
This might look a little weird; however, it is legal C# code. The value on the right of the equal sign is evaluated. In this case, the far right is 123, which is placed into the variable y. Then the value of y is placed into the variable x. The end result is that both x and y equal 123.
|
|
|
Caution |
|
You cannot do operations on the left side of an assignment operator. For |
|
example, you can’t do |
|
|
|
|
|
|
1 + x = y; |
|
|
|
|
|
nor can you put literals or constants on the left side of an assignment operator. |
|
|
|
Mathematical/Arithmetic Operators
Now that you are aware of the punctuators, it is time to jump into the operators. Among the most commonly used operators are the mathematical operators. All the basic math functions are available within C#, including addition, subtraction, multiplication, division, and modulus. Additionally, there are compound operators that make doing some of these operations even more concise.
Working with Operators |
83 |
Note
The modulus operator is also known as the remaindering operator.
Adding and Subtracting
The additive operators within C# are used for addition and subtraction. For addition, the plus operator (+) is used. For subtraction, the minus (-) operator is used. The general format of using these variables is
NewVal = Val1 + Val2; |
|
NewVal2 = Val1 – Val2; |
|
In the first statement, Val2 is being added to Val1 and the result is placed in NewVal. |
|
When this command is done, Val1 and Val2 remain unchanged. Any preexisting values |
|
in NewVal are overwritten with the result. |
|
For the subtraction statement, Val2 is subtracted from Val1 and the result is placed in |
|
NewVal2. Again, Val1 and Val2 remain unchanged, and the value in NewVal2 is overwrit- |
4 |
ten with the result. |
Val1 and Val2 can be any of the value data types, constants, or a literal. You should note that NewVal must be a variable; however, it can be the same variable as Val1 or Val2. For example, the following is legal as long as Var1 is a variable:
Var1 = Var1 – Var2;
In this example, the value in Var2 is subtracted from the value in Var1. The result is placed into Var1, thus overwriting the previous value that Var1 held. The following example is also valid:
Var1 = Var1 – Var1;
In this example, the value of Var1 is subtracted from the value of Var1. Because these values are the same, the result is 0. This 0 value is then placed into Var1 overwriting any previous value.
If you want to double a value, you enter the following:
Var1 = Var1 + Var1;
Var1 is added to itself and the result is placed back into Var1. The end result is that you double the value in Var1.
84 |
Day 4 |
Multiplicative Operators
An easier way to double the value of a variable is to multiply it by two. There are three multiplicative operators commonly used in C#.
Multiplying
The first multiplicative operator is the multiplier (or times) operator, which is an asterisk (*). To multiply two values, you use the following format:
NewVal = Val1 * Val2;
For example, to double the value in Val1 and place it back into itself (as seen with the last addition example), you can enter the following:
Val1 = Val1 * 2;
This is the same as
Val1 = 2 * Val2;
Dividing
To do division, you use the divisor operator, which is a forward slash (/):
NewVal = Val1 / Val2;
This example divides Val1 by Val2 and places the result in NewVal. To divide 2 by 3, you write the following:
answer = 2 / 3;
Working with Remainders
There are times when doing division that you want only the remainder. For example, I know that 3 will go into 4 one time; however, I also would like to know that I have 1 remaining. You can get this remainder using the remaindering (also called modulus) operator, which is the percentage sign (%).For example, to get the remainder of 4 divided by 3, you enter:
Val = 4 % 3;
The result is that Val is 1.
Consider another example that is near and dear to my heart. You have 3 pies that can be cut into 6 pieces, and 13 people each want pie. How many pieces of pie are left over?
To solve this, you first determine how many pieces of pie you have:
PiecesOfPie = 3 * 6; // three pies times six pieces
Working with Operators |
85 |
The value of PiecesOfPie should be obvious to you—18. Now to determine how many pieces are left, you use the modulus operator:
PiecesForMe = PiecesOfPie % 13;
This sets the value of PiecesForMe to 18 Mod 13, which is 5. Listing 4.1 verifies this.
LISTING 4.1 pie.cs—Number of Pieces of Pie for Me
1:// pie.cs - Using the modulus operators
2://------------------------------------------------
3:class pie
4:{
5:static void Main()
6:{
7:int PiecesForMe = 0;
8:int PiecesOfPie = 0;
9: |
|
|
|
10: |
PiecesOfPie = 3 * 6; |
|
|
11: |
|
|
|
12: |
PiecesForMe = PiecesOfPie % 13; |
|
|
13: |
|
|
|
14: |
System.Console.WriteLine(“Pieces |
Of Pie = {0}”, PiecesOfPie); |
4 |
15: |
System.Console.WriteLine(“Pieces |
For Me = {0}”, PiecesForMe); |
16:}
17:}
Pieces Of Pie = 18
Pieces For Me = 5
Listing 4.1 presents the use of the multiplication and modulus operators. Line 10 illustrates the multiplication operator using the same formula as shown earlier.
Line 12 then uses the modulus operator. As you can see from the information printed in lines 14 and 15, the results are as expected.
Compound Arithmetic Assignment Operators
Earlier in today’s lesson, you learned about the basic assignment operator. There are also other assignment operators, the compound assignment operators (see Table 4.1).
TABLE 4.1 Compound Arithmetic Assignment Operators
Operator |
Description |
Non-Compound Equivalent |
||||||
+= |
x += |
4 |
x = x |
+ 4 |
||||
–= |
x |
–= |
4 |
x |
= |
x |
– |
4 |
*= |
x |
*= |
4 |
x |
= |
x |
* |
4 |
86 |
Day 4 |
TABLE 4.1 continued
Operator |
Description |
Non-Compound Equivalent |
||||||
/= |
x |
/= |
4 |
x |
= |
x |
/ |
4 |
%= |
x |
%= |
4 |
x |
= |
x |
% |
4 |
|
|
|
|
|
|
|
|
|
The compound operators provide a concise method for performing a math operation and assigning it to a value. If you want to increase a value by 5, you use the following:
x = x + 5;
or you can use the compound operator:
x += 5;
As you can see, the compound operator is much more concise.
Tip
Although the compound operators are more concise, they are not always the easiest to understand in code. If you use the compound operators, make sure that what you are doing is clear or remember to comment your code.
Doing Unary Math
All the arithmetic operators you have seen so far have been binary. Each has required two values to operate. There are also a number of unary operators that work with just one value or variable. The unary arithmetic operators are the increment operator (++) and the decrement operator (––).
These operators add 1 to the value or subtract 1 from the value of a variable. The following example:
++x;
adds 1 to x. It is the same as saying
x = x + 1;
Additionally, the following:
--x;
subtracts 1 from x. It is the same as saying
x = x – 1;
Listing 4.2 shows the increment and decrement operators in action.
Working with Operators |
87 |
Tip
The increment and decrement operators are handy when you need to step through a lot of values one-by-one.
LISTING 4.2 count.cs—Using the Increment and Decrement Operators
1:// count.cs - Using the increment/decrement operators
2://----------------------------------------------------
4:class count
5:{
6:static void Main()
7:{
8:int Val1 = 0;
9:int Val2 = 0;
11: System.Console.WriteLine(“Val1 = {0} Val2 = {1}”, Val1, Val2); 12:
13:++Val1;
14:--Val2;
16: |
System.Console.WriteLine(“Val1 = {0} Val2 = {1}”, Val1, Val2); |
4 |
17: |
|
18:++Val1;
19:--Val2;
21:System.Console.WriteLine(“Val1 = {0} Val2 = {1}”, Val1, Val2);
22:}
23:}
Val1 = 0 Val2 = 0
Val1 = 1 Val2 = -1
Val1 = 2 Val2 = -2
This listing doesn’t do anything spectacular; however, it does illustrate the increment and decrement operators. As you can see in lines 8 and 9, two variables are
initialized to 0. Line 11 prints this so that you can see they are actually 0. Lines 13 and 14 then increment and decrement each of the variables. Line 16 prints these values so you can see that the actions occurred. Lines 18 to 21 repeat this process.
Using Preand Post-Increment Operators
The increment and decrement operators have a unique feature that causes problems for a lot of newer programmers. Assume that the value of x is 10. Look at the following line of code:
y = ++x;
88 |
Day 4 |
After this statement executes, what will the values of x and y be? You should be able to guess that the value of x will be 11 after it executes. The value of y will also be 11. Now consider the following line of code. Again consider the value of x to start at 10.
y = x++;
After this statement executes, what will the values of x and y be? If you said they would both be 11 again, you are wrong! After this line of code executes, x will be 11; however, y will be 10. Confused?
It is simple. The increment operator can operate as a pre-increment operator or a postincrement operator. If it operates as a pre-increment operator, the value is incremented before everything else. If it operates as a post-increment operator, it happens after everything else. How do you know if it is pre or post? Easy. If it is before the variable, ++x, it is pre. If it is after the variable, x++, it is post. The same is true of the decrement operator. Listing 4.3 illustrates the pre and post operations of the increment and decrement operators.
LISTING 4.3 prepost.cs—Using the Increment and Decrement Unary Operators
1:// prepost.cs - Using preversus post-increment operators
2://----------------------------------------------------
3:
4:class prepost
5:{
6:static void Main()
7:{
8:int Val1 = 0;
9:int Val2 = 0;
11: System.Console.WriteLine(“Val1 = {0} Val2 = {1}”, Val1, Val2); 12:
13:System.Console.WriteLine(“Val1 (Pre) = {0} Val2 = (Post) {1}”,
14:++Val1, Val2++);
15:
16:System.Console.WriteLine(“Val1 (Pre) = {0} Val2 = (Post) {1}”,
17:++Val1, Val2++);
18:
19:System.Console.WriteLine(“Val1 (Pre) = {0} Val2 = (Post) {1}”,
20:++Val1, Val2++);
21:}
22:}
OUTPUT |
Val1 = 0 Val2 = 0 |
|||
Val1 (Pre) = 1 |
Val2 = (Post) 0 |
|||
|
Val1 |
(Pre) = |
2 |
Val2 = (Post) 1 |
|
Val1 |
(Pre) = |
3 |
Val2 = (Post) 2 |