Vous êtes sur la page 1sur 20

Introduction to C#

Introduction to C#
Objectives
Learn about the history of C# and .NET. Understand the goals of C#. Provide a context for .NET and C#.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

1-1

Introduction to C#

Welcome to C#
This course teaches you how to build Windows and Web applications using C# and the .NET platform. .NET represents a significant innovation in the development of Windows and Web programming, and C# is the language of choice for use with the .NET platform.

The Goals of C#
C# is designed to be: Simple Safe Object-oriented Internet-centric High performance

C# is a simple language with only 80 keywords and a dozen types. It is a typesafe language, which means that it enlists the compiler in helping you find bugs while you develop your program. C# builds on the lessons learned from C++ and Java to provide a fully objectoriented approach to design and programming. Object-oriented languages allow you to create new types that reflect the objects in your problem domain. This allows you to manage very complex projects and build programs that are easy to maintain and extend. C# is highly Internet-centric; the goal of C# and .NET is to integrate the Web into desktop applications and to facilitate the development of Web applications. Finally, C# does not sacrifice the high performance characteristics of the C family of languages.

Introducing the .NET Platform


The .NET platform was introduced in July 2000 at the Microsoft Professional Developers Conference (PDC). .NET created quite a sensation; here was a revolutionary approach that provided an object-oriented, component-based layer on top of Windows to facilitate desktop and Web application development. This was essentially a whole new API for Windows and for the Web, presented as a tightly integrated object-oriented framework.

1-2

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Welcome to C#
As time went on we came to discover that .NET was an umbrella for a number of new technologies emerging from Microsoft, including: COM+ ADO.NET ASP+ (now ASP.NET) XML Web Service Protocols SOAP WSDL UDDI

COM+ provides transaction support and messaging for both desktop and Web applications. While the COM+ technology was developed independently of .NET it is fully integrated into the .NET platform. ADO.NET is the successor technology to ADO and provides an objectoriented approach to database interaction. ADO.NET differs from ADO in that it is centered around a disconnected dataset, allowing for greater scalability in the development of database applications. ASP.NET is the replacement technology for ASP, which is Microsofts Web Application development technology. ASP.NET provides a highly scalable, object-oriented, component-based Rapid Application Development environment for building Web applications. XML is the open standards technology for document markup. While all of .NET is built on XML, it is not necessary to become proficient in XML to work with .NET. Visual Studio.NET and the supporting technologies encapsulate and hide the gritty details of XML. Microsoft has made a strong commitment, however, to building .NET on top of open standards such as SOAP: the Simple Object Access Protocolan open, lightweight XML-based standard for the exchange of information in a decentralized and distributed environment.

New Tools
.NET provides a number of new tools, including a suite of new languages (VB.NET, C#, etc.). One of the most powerful new tools is the new integrated development environment: Visual Studio .NET. Visual Studio .NET is an extension of the rapid application development environment previously found in Visual Basic 6, combined with the best elements of FrontPage and the other Microsoft development tools.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

1-3

Introduction to C#
In addition, the new .NET platform provides a comprehensive class library to support many common programming tasks.

New Languages
.NET offers a number of new programming languages, the most important of which are Visual Basic .NET and C#. Visual Basic .NET offers a Visual Basic-like syntax for a fully object oriented language. C# offers a C++-like syntax for the .NET platform. The focus of this course will be on C#. C# is a revolutionary advance in the Clanguage family that previously included C and C++ and, arguably, Java. C# learns lessons from all three, maintaining the performance of C, the overall syntax of C++, and borrowing many innovations from Java, such as garbage collection for memory management. The .NET goal is to provide a language independent development environment. It is possible to write .NET classes in any language that supports the Common Language Specification (CLS). The CLS dictates the characteristics of any conforming .NET language. All CLS languages are integrated with one another, allowing you to create a class in C# and derive from it in Visual Basic .NET, treating both classes polymorphically. In addition, you can throw an exception in a Visual Basic .NET class and catch it in a C# class. All of these concepts: deriving classes, polymorphism, and throwing exceptions will be explained as you go forward.

CTS and CLS


The Common Language Specification (CLS) declares the functionality that any .NET language must support. Part of the CLS is the definition of a Common Type System (CTS). Thus, every language within .NET will support the same set of intrinsic (built-in) types. Currently there are four official languages, though Microsoft expects many more to be forthcoming: C# Visual Basic .NET C++ with managed extensions JScript.NET

Any CLS language can be used to interact with the Framework Class Library. The class library offers a comprehensive suite of useful objects for your 1-4 C# Professional Skills Development
Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Welcome to C#
programming. Youll learn how the Framework Class Library works in great detail throughout this class.

Common Language Runtime (CLR)


The CLR offers an object-oriented platform for Windows and Web development. It is the CLR that interprets your code and acts as an intermediary between your .NET application and the underlying platform. The CLR houses the Just In Time (JIT) Compiler and the intrinsic types as well as support for exceptions.

.NET Architecture
The .NET Framework is built on top of the CLR, which in turn sits on top of the Windows platform, as shown in Figure 1.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

1-5

Introduction to C#

Figure 1. .NET architecture.

The .NET Framework classes are built on top of the CLR and provide extensive low-level support for your application. The Framework Classes provide the plumbing you would otherwise write yourself, including classes for threads, streams, security, and so forth. ADO.NET is the database support technology for .NET. ADO.NET is built on top of the Framework Classes and provides a high level abstraction of database tables and database relationships. Youll learn about ADO.NET in greater detail later in this course. On top of all of this technology lies the support for building Windows applications, Web applications, and Web Services. Web Services are Web applications without a user interface. Web Services provide data and functionality to other Web applications (e.g., a Web Service might provide a stock ticker symbol given the name of a company). C# is the programming language of choice for every layer of this architecture. Much of the CLR, and nearly all of the .NET Framework, is written in C#. C# 1-6 C# Professional Skills Development
Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Welcome to C#
is ideal for writing ADO.NET applications and certainly C# is the right language for building Windows or Web applications.

MSIL
The programs you write in C# are not actually compiled into executable code. Instead your source code (the English text you write) is compiled into an intermediate form called Microsoft Intermediate Language (MSIL) or IL for short. The reason that all .NET languages can interoperate is that the IL code produced by C# is nearly identical to the IL code produced by Visual Basic .NET.

Key Terms
Source code MSIL The English-like text that you type into a file. Microsoft Intermediate Language (MSIL) is the intermediate form your program is transformed into by the compiler. The .NET CLR (Common Language Runtime) transforms the MSIL code into executable code when your program is run.

History of C#
C# was created by Anders Hejlsberg and Scott Wiltamuth. Hejlsberg is the creator of Turbo Pascal and Borlands Delphi. They built C# on the shoulders of C, C++, and Java, consciously borrowing the best aspects of these languages and adding innovations of their own to facilitate .NET development. Because C# was specifically built for .NET and is designed to work in the .NET environment, this course focuses on building .NET applications with this powerful language.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

1-7

Introduction to C#

Hello World
It is traditional in programming books to begin with a program that prints the words Hello World to the monitor. This course will be no exception. Youll start by examining a simple Hello World program.

Source Code
A program consists of source code that you type into a file. You compile the source code file into IL (Microsoft Intermediate Language). You run your program and the CLR turns the IL into executable code. This is known as Just In Time compiling. The compiled code is then cached in memory; the next time you run that block of code it is ready to go. Lets look at a very first program:
namespace HelloWorld { class HelloWorld { static void Main() { // use the system console object System.Console.WriteLine("Hello world"); } } }

Though it is very simple, this program illustrates many concepts in C# programming. Lets take it apart, piece-by-piece. One of the first things you should notice is the keyword class in the third line:
class HelloWorld

A class creates a new type. A type is a thing. The world is filled with things; and we as humans cant help noticing them. Your desk, phone, and chair are things. Your dog, sister, and children are things. The sky is a thing, the idea of 1-8 C# Professional Skills Development
Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Hello World
love and honor are things. We are a thing-oriented species, and C# is a thingoriented language. Some things are concrete, like dogs and desks, and some things are abstract, like love and freedom. C# is able to represent both concrete and abstract things. A class defines a new thing. An object is an instance of a class. Just as dog describes an idea but Fido is an instance of a dog, a class describes a type and an object is an instance of that type. The class button tells you what buttons are like, the edit, cancel, and delete buttons are instances of button, in other words, they are objects. Classes defined new types. From a C# perspective, a type describes the size and capabilities of objects. C# provides a number of built-in types such as int, long, and double, and you are free to create your own types.

Methods
Lets look inside the body of the HelloWorld class:
static void Main() { // use the system console object System.Console.WriteLine("Hello world");

Every class has properties and behaviors. In fact, in C# everything that happens, happens within a class. So class is not only a keyword, it is a key concept. The behavior of a class is defined by its methods (member functions). Methods are typically given action names such as AddNumber or WriteLine. Every program must have a special method, Main. Main does not have an action name, but it does have a special role in every program: it is the entry point. That is, the program begins by calling the Main method. Main must be marked with the keyword static. Youll understand the meaning of the static keyword later in this course; for now you just need to know that Main() must be marked as static. A method has a name, parameters, and a return type. If the method does not return a value it is marked void. You call a method and when it completes, it returns.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

1-9

Introduction to C#
For example, if you add a method, myMethod, you will indicate its parameters within parentheses, and its return type before the name of the method.
void myMethod(int param1, string param2) { // do work here }

The method name is myMethod. The return type is void. This method takes two parameters. The first is an int (integer) and the second is a string. Somewhere else in your code you might invoke that method.
int x = 5; string myString = Hello; myMethod(x,myString);

You declare a couple of local variables: x of type int and myString of type string and then pass these variables as parameters to the method MyMethod. You can declare local variables within any method. These variables are local to the method itself and are destroyed with the method ends. In addition, you can pass in parameters, as you saw here, and these parameters act just like local variables within the method. Youll learn about variables, strings, integers, and parameters in great detail later in this course. The key concept, however, is that methods are useful when you want to provide behavior for your class. Typically, methods are used to manipulate the class data or to interact with other objects.

Comments
In this simple example, you see that there is one line that begins with a pair of slashes:
// use the system console object

This is a comment, which is a note to the programmer that does not affect the program in any way. C# supports three styles of comments: C-style comments /* */ C++ style comments // XML documentation comments ///

1-10

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Hello World
C-style comments begin with a slash-star /* and end with a star-slash */. Everything between the open and end comment marks is commented out. Cstyle comments are very useful for marking large blocks of source code as comments, and most C# programmers reserve them for commenting out code they want to temporarily disable. The most common type of comment used for documenting C# code is the C++ style double slash //. Everything from the double slash to the end of the line is a comment. C++ comments can start in the middle of a line, allowing you to add a comment to the same line as the code itself. The third type of comment is the XML documentation style comment. Youll learn more about this powerful feature later in this course. Comments are a very powerful technique when used well. The key to commenting your code is to write about the purpose of a given line of code, rather than restating what the line of code does. Well-written code is also well commented. Youll be surprised how often youll return to code you wrote and scratch your head thinking, What the devil was I trying to accomplish here? Comments are also very useful for the programmer who inherits your program and needs to understand how it works. Over time you will find that a programmer can never add too many comments.

Console
The last line of the HelloWorld program does all the work:
System.Console.WriteLine("Hello world");

The first thing to note is that this example is a console application. Console applications run in a console window, often called a DOS box. The console is your monitor and a console application simply writes to your console. Console applications are very simple, with virtually no support for Graphical User Interfaces (GUIs). Youll use Console applications a lot early in this course, because they greatly simplify development and allow you to concentrate on the issues at hand, rather than fussing with complex UI issues. In C# the console (monitor) is managed by a console object. WritLine is a method of the Console class. You pass a string as a parameter to the WriteLine method, which in this case is the string Hello World. This string is then printed to the monitor.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

1-11

Introduction to C#

Namespaces
Notice that Console is preceded by System. System is the namespace within which the Console class resides. The Framework Class Library has thousands of useful classes, and each class has a number of methods. That makes for tens of thousands, perhaps hundreds of thousands of names of methods and classes. Namespaces help divide the world of these names to simplify working with classes and to prevent clashes between the names of methods in different parts of the Framework. The dot operator (.) is used to access classes within a namespace. For example, you access the Console class within the System namespace with System.Console. The dot operator is also used to access methods within a class. For example, you access the WriteLine method within the Console class with Console.WriteLine().

1-12

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Building The Application

Building The Application


There are two ways to build the Hello World application. The easiest way is within Visual Studio .Net. Youll be spending a lot of time within the Visual Studio .NET integrated development environment (IDE), but to prove that there is nothing magical about the IDE youll build this first application from the command line.

Try It Out!
1. Open Notepad and copy in the program as shown in Figure 2.

Figure 2. Notepad with Hello World.

2. Save the program as HelloWorld.cs. 3. Open the Visual Studio .NET command prompt from the Start window. This opens a command window set up properly for the .NET compiler. 4. Navigate to the directory in which you stored your program. 5. Enter the command csc HelloWorld.cs This builds the application. 6. Type dir to see a directory of the current folder. You should see at least the following two files: HelloWorld.cs HelloWorld.exe

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

1-13

Introduction to C#
7. Enter HelloWorld from the command prompt. The program should run and print the words Hello World! to your monitor.

Building Applications in Visual Studio .NET


Youve built the application in Notepad and compiled it at the command line. Next you will build the same application from within Visual Studio .NET. With such a simple application as this, Visual Studio .NET does not provide much obvious additional value; and the code it will create will be a bit more complicated. But Visual Studio .NET does offer tremendous advantages with anything but the simplest of code. 1. To get started, open Visual Studio .NET by clicking the Start button. 2. Click on New Project. This opens the New Project dialog box as shown in Figure 3. Be sure to select a Visual C# project in the Project Types window and a Console Application in the Templates window. You may name your program anything you like, and store it in whatever location is convenient for you. When you are ready, click OK.

Figure 3. The New Project dialog box.

1-14

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Building The Application


3. Visual Studio .NET sets up your application and opens a series of Windows to facilitate writing your code, as shown in Figure 4. Notice that the code window offers a starting point for the Main method.

Figure 4. The Hello World application.

4. Within the body of Main, delete the comment and add the following code:
Console.WriteLine("Hello World");

5. Notice that Visual Studio .NET attempts to help you choose the right method from Console, and offers supporting information about the parameters expected for WriteLine. Your code should now look like Figure 5.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

1-15

Introduction to C#

Figure 5. Hello World.

6. Note that the Main method is written somewhat differently by Visual Studio .NET. In this version of Main() there is an argument named args. Youll ignore this for now. This is useful when calling a C# application from the command line, but is not relevant to the current program. 7. Save this program by pressing CTRL+S or by clicking the Save button, as shown in Figure 6.

Figure 6. The Save button.

8. Build this program by pressing CTRL+SHIFT+B or by selecting Build>Build from the menu. You should see Build: 1 succeeded, 0 failed, 0 skipped in the Output window. 9. Run the program by pressing CTRL+F5 or selecting Debug->Start Without Debugging from the menu. You should see a console window open and the text display, as shown in Figure 7.

Figure 7. Running the program.

1-16

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Building The Application


10. Notice that Visual Studio .NET keeps the window open and adds the prompt Press any key to continue. This prompt is provided for you by the IDE, and you do not need to modify your program to create this prompt.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

1-17

Introduction to C#

Summary
The .NET platform supports a Common Language Specification detailing how languages must behave. The CLS includes a Common Type Specification (CTS) detailing the types for all .NET languages. C# is ideally suited for work with the .NET platform. The Hello World program illustrates the fundamentals of writing a C# program. The steps are: write the program, compile it and run it. The output of compiling the program is Microsoft Intermediate Language (MSIL). The Common Language Runtime (CLR) turns the IL code into an executable program in a process known as Just In Time Compiling.

1-18

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Building The Application

Questions
1. What is the Common Language Specification? 2. What is ADO.NET? 3. What is MSIL? 4. What are the three types of Comments?

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

1-19

Introduction to C#

Answers
1. What is the Common Language Specification?
The Common Language Specification (CLS) declares the functionality that any .NET language must support

2. What is ADO.NET?
ADO.NET is the successor technology to ADO; it provides an object model for interacting with back end data providers such as relational databases

3. What is MSIL?
MSIL is Microsoft Intermediate Language. When you compile your program what is produces is an MSIL file that is then compiled by the Just In Time (JIT) compiler. The MSIL produced by C# is virtually identical to the MSIL produced by other CLScompliant languages

4. What are the three types of comments?


C# supports C-style comments (/* */) and C++ style comments (//) as well as the new XML documentation comments (///)

1-20

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Vous aimerez peut-être aussi