Вы находитесь на странице: 1из 20

Chapter 1

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.1 Visual C#.NET


Visual C#.NET 2005 (or simply C#) is one of the latest Microsoft products. It is part
of Visual Studio .NET, which is part of .NET Framework. It is a new programming
language for Console, Windows and Web applications. It is a modern, object-oriented
programming language that enables programmers to quickly build a wide range of
applications for the .NET platform. It provides lots of features and services which you
can use to develop practically any application. The framework enables C# components
to become XML Web services which you can deploy over the Internet for any
application running on any platform.
C# is intended to be an alternative language to Java, C++ and Visual Basic. Its purpose
is twofold:
1. It gives access to features previously available only in C++, while retaining
some of the simplicities of Visual Basic.

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.

1.2 Visual Studio.NET


Visual Studio.NET (VS.NET) is the successor to Visual Studio 6. It comes with a
new language called C# in addition to improved versions of Visual C++ and Visual
Basic. Visual Studio.NET provides an integrated development environment (IDE)
aimed at simplifying the development of .NET applications. It provides project
templates for developing all kinds of applications, be it Windows forms, Web Services,
Active Server Pages (ASP) or applications which require Database connectivity. It also
provides support for HTML, XML and XMLSchema.

1.3 The .NET Framework


The .NET Framework (now Version 2) is Microsofts new computing platform
created to simplify application development, especially for the distributed environment
of the Internet. It serves as the foundation for developing .NET solutions. The .NET
Framework, which is itself a major component of .NET, includes numerous

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:

Common Language Specification


Common Type System
Common Language Runtime (CLR)
Garbage Collector (GC)
Just-In-Time (JIT) Compiler

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

Common Type System


Common Language Runtime

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

1.4 The .NET

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

1.5 System Requirements


The recommended minimum system requirements for running C# programs are as
follows:

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 Visual Studio.NET IDE


On activating Microsoft Visual Studio 2005 you will see the integrated development
environment (IDE) with the main screen (Figure 1.4).
The screen has several parts:
Title bar with the title Start Page - Microsoft Visual Studio.
Menu bar with several menu items such as File, Edit, View, Tools,
Windows, Community and Help. When you click on a menu item, you will see
a pull-down menu giving you several options for that menu item. The pull-down menus
for some of the menu items are shown below. Some of the options in the pull-down
menu have shortcut keys. For example, the shortcut keys for New File (in File
menu) is Ctrl+N and the shortcut key for Undo (in Edit menu) is Ctrl+Z. You
can use the shortcut keys from anywhere on the screen (without having to select a
menu item and then an option).

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

Figure 1.5: C# Menus

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.7 Console 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

3. Click the OK button.


4. Once the project is initialized, you will see the following code in the code window.
We have added one line of code (highlighted) to make the program display Hello
World!
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

5. Select the Debug > Start Without Debugging menu item.


You will see the output screen shown below.

6. Press any key to exit from the application.

1.8 Using Command Prompt


You can also use the Visual Studio 2005 Command Prompt to run a C# program. The
steps are as follows:
1. Create a C# program as in the Console Application above.

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

1.9 Windows Application


To create, compile and run a C# Windows application (say, displaying the Hello
World! message), use the following steps:
1. Create a new project of type Windows Application as shown below.

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

1.10 Compiling & Executing C# Programs


Lets illustrate the steps for compiling and executing another simple C# Console
Application to display a greeting message.
1. Start Visual Studio and select
File > New > Project > Console Application

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]

// these are built-in namespaces


using System;
using System.Collections.Generic;
using System.Text;

[4]
[5]
[6]
[7]

// this is a programmer-defined namespace


namespace ConsoleApplication1
{
// class starts here
class MyClass
{
// Main method starts here
static void Main(string[] args)
{

[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]

3. Save the file as MyClass.cs


4. Compile and run the program. You can do this by selecting
Debug > Start Without Debugging

or Ctrl+F5 as shown below.

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.11 The Parts of A Program


Lets briefly explain the various parts of the above program.
Comments
Comments are added to a program to make it readable. They can appear anywhere in
the program. Comments are not executable statements; the compiler simply ignores
them.
Comments can appear on several lines (lines 1 to 3 in the above code) or on a single
line (line 4, etc). A multi-line comment start with the characters /* and ends with the
characters */. It can span several lines. The pair of characters (/* and */) must
appear together because C# treats them as a single symbol. That means you should not
have any space between them.
A single line comment starts with two forward slashes (//). Everything on that line
after the slashes is treated as a comment. The comment can appear after a statement
(line 17) or it can be on its own (line 20).
Line spacing
Blank lines can be inserted between statements for readability. For example, we have
inserted a blank line between lines 3 and 4. Blank lines are useful to separate methods
or to begin and end a lengthy loop in a program.
Namespace
A namespace consists of a collection of related classes. C# provides numerous built-in
namespaces that users can use to simplify their programming. The basic namespaces
that most C# programs need are System, System.Collections.Generic
and System.Text. To use them, you prefix them with the word Using (lines 5-7).
Note that there is a semicolon at the end of each namespace directive. The semicolon
terminates the statement. This is the basic rule for all executable statements unless they
appear in a block enclosed between the curly braces ({}).

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

Specifies that Main() can be accessed from anywhere such as


from another project.

static

Specifies that Main() is attached to the class (MyClass) and

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.

Compile hello.cs using command > csc hello.cs

11. Enter command > dir *.exe to see whether the executable file hello.exe
has been generated.
Executing/Running
12.

Enter the command > hello to execute the program.

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.

Вам также может понравиться