Chapter 1 Introducing C#
Chapter 1 Introducing C#
Introducing C#
This chapter discusses the following topics:
Visual C#.NET
Visual Studio.NET
The .NET Framework
The .NET
System Requirements
Visual Studio.NET Installation
Visual Studio.NET Development Environment
Console Applications
Windows Applications
Compiling and Executing C# Programs.
1-2 Chapter 1
2. It has been designed specifically with the .NET framework in mind, and hence,
it is well-structured for writing code that will be compiled for the .NET.
Some of the main benefits of using C# are:
It is easy to learn and use. Editing, compiling, running and debugging a C# program
using the integrated development environment (IDE) is easy.
It is powerful and flexible. Its power and flexibility is second to none.
It is object-oriented. C# is completely object-oriented. That means, you have all the
benefits of using object-oriented technology such as modularity, inheritance and
software reuse.
It is robust. The term robust refers to the degree to which an application can handle all
types of situations, both expected and unexpected. The more robust the application, the
better it can withstand errors. Less robust applications usually crash. The C# system
carefully checks each memory access to ensure that it is legal. C# handles errors by
throwing exceptions. That means, you can write code to detect errors and recover from
them successfully. In this way, errors are eliminated or minimized.
Linking modules is dynamic. This feature, also known as delayed or late binding,
offers much flexibility. In delayed or dynamic linking, modules are linked only as and
when they are needed. The modules which are not needed for current program
execution are not linked. This reduces program size and thus saves memory.
Introducing C# 1-3
namespaces (collection of related classes) and interfaces for developing all kinds of
application. By using the .NET Framework, you can develop virtually any application
be it Windows, Networking, Web or Web services with considerable ease.
The .NET Framework basically comprises of three parts as follows:
Class libraries
The Common Language Runtime (CLR)
Services
Class Libraries
The .NET Framework provides numerous built-in or predefined classes organized into
different categories called namespaces. A namespace is used to logically or
semantically group or package related functions. For example, one namespace may
provide building blocks for building Windows applications and another for developing
Web applications. Some of these namespaces may be further divided into more specific
namespaces. For example, the web development namespace may contain a namespace
for developing web services.
The Runtime
The .NET Framework provides several Runtime components which include the
following:
The Common Language Specification (CLS) ensures that code written in different
languages all behave in a uniform way, for example, when an object is instantiated or
when a method is invoked with a value or reference parameter. This is important in
the .NET environment because code written in different languages (e.g., C++, Visual
Basic, JScript) may behave differently without adhering to a set of common rules.
The Common Type System (CTS) defines some basic data types such as Integer,
Double, and String. This facilitates interoperability between languages using the .NET
Framework. In other words, it makes cross-language compatibility possible.
(Remember, in the .NET Framework, you can use different languages to develop an
application.)
1-4 Chapter 1
The Common Language Runtime (CLR) manages the execution of all applications
developed using the .NET library.
Figure 1.1 illustrates cross-language operability via Common Type System and
Common Language Runtime.
Figure 1.1 Cross-language operability
C#
C++
VB
JScript
The Garbage Collector (GC) is a memory manager whose job is to reclaim memory
allocated to objects which are no longer needed such as when an object is deleted or
goes out of scope.
The Just-in-Time (JIT) Compiler compiles the intermediate language (IL) to native
code that is specific to the target machine and operating system. The IL code is
compiled only when it is needed.
The compilation of a C# program from source code to intermediate code to native code
is shown graphically in Figure 1.2.
Figure 1.2: Stages of compilation of a C# program
Introducing C# 1-5
The .NET comprises of the .NET Framework, .NET Services (e.g., development tools
such as Visual Studio) and infrastructure services provided by the .NET Enterprise
Servers (e.g., SQL, Biz Talk). Figure 1.3 gives an overview of .NET.
Figure 1.3: Overview of .NET
.NET/Web Services
.NET Solutions
.NET Enterprise Servers
Web Services
Class Library
Runtime
.NET
Framework
OPERATING SYSTEM
A Pentium IV processor.
512 MB of RAM
1 GB of system disk space, 3 GB of installation disk space.
CD-ROM drive
Windows XP/2000/2003
1-6 Chapter 1
Main Window displays the introductory Start Page when Visual Studio 2005 is
started. This window is tabbed such that we can switch between several files with ease
by clicking on their filenames.
Figure 1.4: Visual Studio 2005 Integrated Development Environment
Title bar
Menu bar
Standard Toolbar
Maximize
Minimize
Minimize Close
Toolbox
Server
Explorer
Solution
Explorer
Window
Properties
Window
Output
Window
Main Window
Server Explorer and Toolbox pop up when the mouse moves over them, and provide
various additional capabilities such as providing access to the user interface building
blocks for windows applications.
Solution Explorer Window displays information about the currently loaded solution.
Properties Window allows a more detailed view of the contents of a project and
allows us to perform additional configuration of individual elements.
Output Window displays information when projects are compiled, along with tasks to
be completed.
Note that some of the options in the pull-down menus are grayed out (Figure 1.5). That
means, they are not available (or applicable) for use for the current context. By
graying out those options that are not permitted, C# prevents the programmer from
clicking at the wrong options, thus minimizing errors.
Introducing C# 1-7
Menu item
Shortcut
keys
The Standard Tool bar, located below the Menu bar, has several icons on it. The
icons represent some of the commonly used functions such as opening a new or
existing file, saving the current file, copying, cutting, pasting and undoing the previous
operation. The icons represent only a subset of the functions. To use other functions
not available on the Standard Toolbar, you must click on the appropriate menu item
and select the desired option.
The Minimize, Maximize and Close buttons perform the same functions as in other
Windows based applications. Clicking the Minimize button creates an icon for the
application and puts the application on the Taskbar. To activate, click the icon on the
Taskbar. Clicking the Maximize button causes the application to fill the entire screen
and clicking it again will cause it to revert to its original size. Clicking the Close button
closes the application.
1-8 Chapter 1
To create, compile and run a C# Console or DOS Application, use the following steps:
1. Create a new console application project by selecting the File > New > Project
2. Select Visual C# Windows from Project Types and the Console Application in
the Templates.
Introducing C# 1-9
1-10 Chapter 1
2. Select File > Save Program.cs As
3. Name the file as MyClass and store it in the C drive as shown below.
4. Select Start > Programs > Microsoft Visual Studio 2005 >
Visual Studio Tools > Visual Studio 2005 Command Prompt.
5. At the Command prompt, change to C drive, compile and run as shown below.
Introducing C# 1-11
2. Move the mouse pointer to the Toolbox bar on the left of the screen. Select All
Windows Forms and double click the mouse on the Button icon to add a command
button to the main form of the application.
1-12 Chapter 1
3. To add code for the button, double click on the button that you just added to the
form.
4. You will see many lines of code. Go to the button1_Click method and add the
highlighted code as shown below.
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello World!");
}
The command pops up a message box and displays the Hello World!
message.
5. Select Debug > Start Debugging (or F5) to run the application.
6. Click on the button (button1) and the program will output Hello World! in a
message box as shown below.
Introducing C# 1-13
2. Type the highlighted code (minus the line numbers) in the code window.
/* This is a multi-line comment statement; the program
asks the user to enter his/her name and displays the
message Good day with the users name */
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
[10]
[11]
[12]
[13]
[14]
[15]
[16]
1-14 Chapter 1
string name; // variable declaration
Console.Write("Enter you name: "); // a prompt
name = Console.ReadLine(); // input statement
// the line below is an output statement
Console.WriteLine("Good day, " + name);
}
}
}
[17]
[18]
[19]
[20]
[21]
[22]
[23]
[24]
Note that the program is compiled automatically when you run it. So you dont have to
explicitly compile the program.
The above program will produce the output
Introducing C# 1-15
1-16 Chapter 1
The directives in these namespaces provide basic classes that all C# programs will
need. For example, the System namespace provides the Console class for reading
input data and for displaying output. Associated with this class are methods such as
ReadLine()(line 19), Write()(line 18), and WriteLine()(line 21).
Keywords
Keywords (also called reserved words) have special meaning in C#. As such, they
can only be used for their intended purpose; you cannot use them for any other
purpose. For example, in the above code the words Using and System (line 5) are
keywords (there are also other keywords in the code such as class, static,
public, void and string).
Case sensitivity
C# is case-sensitive (unlike Visual Basic or Pascal). That means uppercase and
lowercase letters do matter when coining a namespace, function or variable name. For
example, if you had typed the word system instead of System in line 5, the
compiler will give you an error message. Similarly, the variables name, Name and
NAME are all different. So you must be case-conscious when you code your program.
Class
As C# is an object-oriented language, a C# program must have at least one class. In
the above program, line 5 declares the class called MyClass. It is preceded by the
keyword class. You can coin your own class name. However, to make sense, you
must give a meaningful name. The body of a class is enclosed between a pair of braces
({}) (lines 13 to 24).
Main() method
A program can have one or more methods and it must include the method Main()
(line 15). The body of a method is enclosed between a pair of curly braces ({}) (lines
16 to 23).
Program execution in C# always starts at Main(). The keywords public,
static and void before Main()have certain meanings:
public
static
Introducing C# 1-17
not to an instance of that class.
void
Specifies that Main() will not return any value to the calling
program (operating system in this case).
Most of the time you will need all these three keywords when writing your Main()
method.
Parameters
The curved brackets () following Main is used to specify any parameter(s) that the
method might need. Our program doesnt require any parameters, hence there are no
parameters enclosed in the brackets. The brackets are still needed even if a method
does not require any parameters.
Variable declaration
Line 9 declares a variable called name of type string. The word string is a
keyword used to declare string variables (consisting of a set of alphanumeric
characters).
A variable is used to store a data item, in this case, to store the name of a person. A
variable must begin with a letter and may be followed by one or more letters, digits
and/or underscores (_). Special characters (e.g., @, %, *) are not allowed in a
variable. Blanks are also not allowed in a variable. A variable can be anywhere from 1
to 255 characters long. However, in practice, a variable seldom exceeds 30 characters.
To make sense, you must coin meaningful names for your variables.
Input statement
Most programs will require some sort of input. In the above program, the statement (at
line 19)
name = Console.ReadLine();
reads data (name) from the keyboard and then assigns the data to the variable name.
The ReadLine()method on the right-hand side of the = sign is part of the
Console class. It reads text data from the console (keyboard).
Assignment statement
The above statement is also an assignment statement. The operator = is an assignment
operator (not an equal sign). In an assignment statement, the value of the expression on
the right-hand side of the assignment operator is evaluated and the result is assigned to
the variable on the left-hand side of the operator. The expression can be a simple
1-18 Chapter 1
number, a variable, an algebraic expression or a function/method call which returns a
value. In this case, it is a method call to read a line of text.
Output statement
Most programs will also produce some output (or report). There are two output
statements in the above program (lines 18 and 21). The statement
Console.Write("Enter you name: ");
asks the user to enter a name, i.e., it displays a message (or prompt) on the system
console (screen). The Write method (which is part of the Console class) displays
the message enclosed between the pair of double quotes (). After executing the
statement, the cursor will be positioned on the same line immediately after the prompt.
The statement (at line 21)
Console.WriteLine("Good day, " + name);
is similar to the above statement but it will position the cursor on the next line after
displaying the message Good day, followed by the name the user enters. The
operator + acts as a concatenation operator. It is used to concatenate (join) the message
and the name entered by the user. For example, if the name entered is Sellappan, the
program will output
Good day, Sellappan
Note: Dont worry if you dont quite understand the above code (program). The code is
given here just to help you see how a C# program looks like. As you progress through
the book, especially Chapters 3 and 4, you will begin to understand the various parts
of a C# program.
Exercise
1.1 Explore the Visual Studio 2005 Development Environment to view some of the
features available.
1.2 Click on each menu item on the menu bar and explore the functions provided.
1.3 Create a simple DOS (console) application using the steps given in the chapter.
Introducing C# 1-19
1.4 Create a simple Windows application using the steps given in the chapter.
1.5 Explore the debugging facilities provided by C#.
1.6 C# programming can also be carried out without the use of an Integrated
Development Environment such as Visual Studio 2005. Try editing and running the
Hello World! program using DOS command line approach given below:
Editing
1. Select Start > Program > Accessories > WordPad to create a blank text file.
2. Edit the following sample C# program into the blank file :
class Hello
{
static void Main()
{
System.Console.WriteLine("Hello World!") ;
}
}
3. Select the WordPad pull-down menu File > Save As to pop out Save As menu.
4. Use this menu to save the file you have edited. First select the proper folder for it,
e.g., C-Sharp. Next, give it a name hello.cs and save it as Text Document
MS-DOS format.
Compiling
5. Select Start > Program > Accessories > Command Prompt to activate DOS-like
command prompt window.
6. Make sure that path C:\WINNT\Microsoft.NET\Framework\v2.0.50727 is in
the environment variable path. This is where the C# compiler csc.exe is. You can
check for the existence of this path by entering command >path. If the path does
not exist, refer to instruction on how to edit the path variable. Please take note that
this path may vary if different version of Microsoft .NET Framework is used.
7. Go to the directory where the target program is, e.g., > cd C-Sharp.
8. List out the content of the C-Sharp directory using command > dir/p to see
whether hello.cs is there.
9. Enter command > type hello.cs to see the content of hello.cs.
1-20 Chapter 1
10.
11. Enter command > dir *.exe to see whether the executable file hello.exe
has been generated.
Executing/Running
12.
1.7 Repeat the steps in Exercise 1.6 to develop a Windows/GUI version of the Hello
World! program and save it as GUIhello.cs. Use the command > csc
/Target:winexe GUIhello.cs for Step 10.