Professional Documents
Culture Documents
Chapter 1
Chapter 1
1
C#
In 2000, Microsoft announced the C# programming language. C# has roots in the C, C++
and Java programming languages. It has similar capabilities to Java and is appropriate for
the most demanding app-development tasks, especially for building today's large-scale
enterprise apps, and web-based, mobile and “cloud”-based apps.
Event-Driven Programming
C# is event driven. You’ll write programs that respond to user-initiated events such as
mouse clicks, keystrokes, timer expirations and new in Visual C# 2012 touches and finger
swipes gestures that are widely used on smartphones and tablets.
Visual Programming
Microsoft's Visual C# is a visual programming language—in addition to writing program
statements to build portions of your apps, you’ll also use Visual Studio's graphical user
interface (GUI) to conveniently drag and drop predefined objects like buttons and
textboxes into place on your screen, and label and resize them. Visual Studio will write
much of the GUI code for you.
Microsoft’s .NET
In 2000, Microsoft announced its .NET initiative (www.microsoft.com/net), a broad
vision for using the Internet and the web in the development, engineering, distribution
and use of software. Rather than forcing you to use a single programming language, .NET
permits you to create apps in any .NET-compatible language (such as C#, Visual Basic,
Visual C++ and many others). Part of the initiative includes Microsoft’s ASP.NET
technology.
.NET Framework
The .NET Framework executes apps and contains the .NET Framework Class Library,
which provides many capabilities that you’ll use to build substantial C# apps quickly and
easily. The .NET Framework Class Library has thousands of valuable prebuilt classes that
have been tested and tuned to maximize performance. You’ll learn how to create your own
classes, but you should re-use the .NET Framework classes whenever possible to speed up
the software development process, while enhancing the quality and performance of the
software you develop.
2
security, automatic memory management and more. Unmanaged-code programs do not
have access to the CLR’s services, which makes unmanaged code more difficult to write.5
Managed code is compiled into machine-specific instructions in the following steps:
First, the code is compiled into Microsoft Intermediate Language (MSIL). Code
converted into MSIL from other languages and sources can be woven together by the
CLR—this allows programmers to work in their preferred .NET program- ming language.
The MSIL for an app’s components is placed into the app’s executable file—the file
that causes the computer to perform the app’s tasks.
When the app executes, another compiler (known as the just-in-time compiler or JIT
compiler) in the CLR translates the MSIL in the executable file into machine-language
code (for a particular platform).
The machine-language code executes on that platform.
Platform Independence
If the .NET Framework exists and is installed for a platform, that platform can run any
.NET program. The ability of a program to run without modification across multiple
platforms is known as platform independence. Code written once can be used on another
type of computer without modification, saving time and money. In addition, software can
target a wider audience. Previously, companies had to decide whether converting their
programs to different platforms q—a process called porting—was worth the cost. With
.NET, porting programs is no longer an issue, at least once .NET itself has been made
available on the platforms.
Language Interoperability
The .NET Framework provides a high level of language interoperability. Because soft-
ware components written in different .NET languages (such as C# and Visual Basic) are
all compiled into MSIL, the components can be combined to create a single unified
program. Thus, MSIL allows the .NET Framework to be language independent.
begins with //, indicating that the remainder of the line is a comment. You’ll insert com-
ments to document your apps and improve their readability. The C# compiler ignores
comments, so they do not cause the computer to perform any action when the app is run.
3
We begin every app with a comment indicating the figure number and the name of the
file in which the app is stored.
A comment that begins with // is called a single-line comment, because it terminates at
the end of the line on which it appears. A // comment also can begin in the middle of a
line and continue until the end of that line (as in lines 7, 11 and 12).
Welcome to C# Programming!
using Directive
Line 3
using System;
is a using directive that tells the compiler where to look for a class that’s used in this
app. A great strength of Visual C# is its rich set of predefined classes that you can
reuse rather than “reinventing the wheel.” These classes are organized under
namespaces—named collections of related classes. Collectively, .NET’s namespaces
are referred to as the .NET Framework Class Library. Each using directive
identifies a namespace containing predefined classes that a C# app should be able to use.
The using directive in line 3 indicates that this example intends to use classes from
the System namespace, which contains the predefined Console class (discussed shortly)
4
used in line 10, and many other useful classes.
For each new .NET class we use, we indicate the namespace in which it’s located. This
information is important, because it helps you locate descriptions of each class in the .NET
documentation. A web-based version of this documentation can be found at
msdn.microsoft.com/en-us/library/ms229335.aspx
This can also be accessed via the Help menu. You can click the name of any .NET class or
method, then press the F1 key to get more information. Finally, you can learn about the
contents of a given namespace by going to
msdn.microsoft.com/namespace
So, msdn.microsoft.com/System takes you to namespace System’s documentation.
Blank Lines and Whitespace
Line 4 is simply a blank line. Blank lines and space characters make code easier to read, and
together with tab characters are known as whitespace. Space characters and tabs are known
specifically as whitespace characters. Whitespace is ignored by the compiler.
Class Declaration
Line 5
public class Welcome1
begins a class declaration for the class Welcome1. Every app consists of at least one class
declaration that’s defined by you—the programmer. These are known as user-defined
classes. The class keyword introduces a class declaration and is immediately followed by
the class name (Welcome1). Keywords (sometimes called reserved words) are reserved for
use by C# and are always spelled with all lowercase letters. The complete list of C# key-
words is shown in Fig. 3.2.
5
C# Keywords and contextual keywords
Contextual Keywords
add alias ascending Async await
by descending dynamic Equals from
get global group Into join
let on orderby Partial remove
select set value Var where
yield
Welcome
to
C#
Programming!
6
Fig. 3.12 | Some common escape sequences. (Part 1 of 2.)
Escape
line—does not advance the cursor to the next line. Any characters output after
the carriage return overwrite the characters previously output on that line.
Backslash. Used to place a backslash character in a string.
Welcome to
C# Programming!
7
// Displaying the sum of two numbers input from the keyboard.
using System;
4
5 public class Addition
6 {
// Main method begins execution of C# app
public static void Main( string[] args )
9 {
10
11
12
13
Console.Write( "Enter first integer: " ); // prompt user
// read first number from user
number1 = Convert.ToInt32( Console.ReadLine() );
17
Console.Write( "Enter second integer: " ); // prompt user
Fig. 3.14 | Displaying the sum of two numbers input from the keyboard. (Part
1 of 2.)
Fig. 3.14 | Displaying the sum of two numbers input from the keyboard. (Part 2 of 2.)
Arithmetic
Most apps perform arithmetic calculations. The arithmetic operators are summarized in
Fig. 3.18. Note the various special symbols not used in algebra. The asterisk (*) indicates
multiplication, and the percent sign (%) is the remainder operator (called modulus in some
languages), which we’ll discuss shortly. The arithmetic operators in Fig. 3.18 are binary
operators—for example, the expression f + 7 contains the binary operator + and the two
operands f and 7.
If both operands of the division operator (/) are integers, integer division is per-
formed and the result is an integer—for example, the expression 7 / 4 evaluates to 1, and
the expression 17 / 5 evaluates to 3. Any fractional part in integer division is simply trun-
cated (i.e., discarded)—no rounding occurs. C# provides the remainder operator, %, which
yields the remainder after division. The expression x % y yields the remainder after x is
8
Arithmetic Algebraic C#
C# operation operator expression Expression
Addition + f +7 f +7
Subtraction – p–c p -c
Multiplication * b m b *m
x
Division / x / y or -- or x y x /y
y
Remainder % r mod s r % s
Evaluated first
* Multiplication If there are several operators of this type,
/ Division they’re evaluated from left to right.
% Remainder
Evaluated next
+ Addition If there are several operators of this type,
- Subtraction they’re evaluated from left to right.
Relational operators
> x > y x is greater than y
< x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Equality operators
== x == y x is equal to y
!= x != y x is not equal to y
from the user, extracts the integers from that text with the ToInt32 method of class
Con- vert, and stores them in variables number1 and number2. Then the app
compares the num- bers and displays the results of the comparisons that are true.
// Fig. 3.22: Comparison.cs
// Comparing integers using if statements, equality operators
// and relational operators.
using System;
5
6 public class Comparison
7 {
// Main method begins execution of C# app
public static void Main( string[] args )
10 {
int number1; // declare first number to compare
int number2; // declare second number to compare
13
// prompt user and read first number
Console.Write( "Enter first integer: " );
number1 = Convert.ToInt32( Console.ReadLine() );
17
// prompt user and read second number
Console.Write( "Enter second integer: " );
number2 = Convert.ToInt32( Console.ReadLine() );
21
22
23
24
25
26
27
28
10
29
30
31
32
33
34
35
36
37
38
} // end Main
} // end class Comparison
Fig. 3.22 | Comparing integers using if statements, equality operators and relational
operators. (Part 1 of 2.)
Fig. 3.22 | Comparing integers using if statements, equality operators and relational
operators. (Part 2 of 2.)
11
This page intentionally left blank
12