[edit] C# Introduction Tutorial
Welcome to the all new exciting young world of C#. Why do we say it is young? Simply because it’s still in the process of evolving and quite unexplored, underutilized, its full potential still obscure to many users in the programming community. C# (pronounced as C sharp) is the brainchild of the Microsoft Foundation, and part of its .Net framework, a common platform to develop various applications in wide areas of technology starting from the desktop, to the internet and distributed computing under a single roof on a single base. Don’t panic if you are hearing these words for the first time as we’ll be explaining everything in due course.
We give a complete round tour of the language itself, elaborating on points that draw our attention at first glance, and stressing various constructs which throw open new possibilities for the reader, urging them to think in new dimensions. We would like to be of assistance equally to a novice programmer starting off with C#, and an expert programmer flipping through to find specific information on the content. We encourage you to read it from the beginning giving out time to think and revel upon the information given out in each section and grasp all the basic constructs as we walk you through them.
So, let’s get started………..
[edit] What you will Learn in this C# Tutorial
This tutorial is written for a person new to programming to experts wanting syntax clarification. I will touch on Microsofts C# RAD development tool, C# basic programming concepts and rules. I will also cover the .NET Framework unique feature called intellisense which allows the programmer to complete a statement without typing the whole word or command. Take a look at the menu sidebar you can navigate through this tutorial by clicking on topics in the sidebar. Take note that some topics have subtopics which will explain a given topic in further detail. C# code examples will be short so you can quickly follow what is going on. If you cannot afford the .NET Visual Studio there is an alternative - the .NET Framework SDK. It is everything you need to write any .NET application.
[edit] A little Microsoft Programming History
In the beginning, there were only two numbers available to program, a 0 and a 1. When one imagines the power of the early programmer who used only these to write out elaborate programs, we can’t just imagine what they have been through. Thanks to all those people who saw the need for human readable languages and developed such beautiful languages like Basic, C and C++.
So, what is a program? A Program, in its very simplest form is just a set of instruction for the computer to perform for a desired result. That’s all it is, simple isn’t it? It’s these humble beginnings that spun the whole race of programming languages. When we say “race” of programming language we mean to say that, each language is not a separate identity but related to one another, as each new language is influenced by an older one, where the latter lacked some essential features that we (the programmers) felt the need and developed the former to finish the gap. For some, the new language coexists with the older ones, for others they are replaced. This is how programming languages have evolved and the very art of programming is alive and kicking. Our C# is also no exception, and it is also inspired by some of the older languages.
The creation of C triggered the beginning of the modern age of programming, invented by Dennis Ritchie in the 1970s which exclusively used the UNIX platform. C eventually had grown out of the revolution of Structured programming (we would be elaborating on that soon) which gave programmers to track down the flow of execution of the program they had written as with the size (no of lines in the program) grew complexity and inadequacy to track down anomalies (called as bugs), which prevented the program to give out the desired results. Imagine if you had written a 10,000 + lines of program and when you execute it, it doesn’t work the amount of frustration you are put through. Although many other languages at the time used the same concept but C became the most popular and adapted language for its easy-to-use syntax and the fact that programmer was in control of the execution.
C hit its roadblock when projects become larger in size and slip into unmanageable program execution. In order to handle this solve this situation a new concept of programming evolved known as object-oriented programming (OOP – we’ll explain as we go ahead) and due to its inability to support this revolutionary idea, a new language was developed known as C++. All through the mid 1980’s C++ was undergoing extensive development and C still remained popular. But when C++ hit out 1990s, programmers headed for it immediately for ultimate flexibility and utility at that time. C++ was not a brand new language but just an enhancement of the already most popular language C.
Java was the next milestone towards the evolution of C#, which was developed from 1991 by Sun Microsystems. It’s an object oriented language and derived from C++. Java was evolution was not driven by the art of programming rather by the changes in the computing world which saw a tremendous breakthrough in the form of internet and a need for programs which are not specific to a particular make (made a particular manufacturer) and can be executed on every computer with any operating system (like Windows, MAC) as wide variety of users with their own preferred system connected to the internet. Although the main target was not internet but to be portable for microcontrollers, but Java found its extensive use in programming for the internet.
Before moving on to C#, we would like to take a detour and show you how actually our program gets interpreted and executed by on our computers. Each programming language has its own mechanism to convert our human readable instructions (programs) to be converted into machine readable programs (binary). There are two major ways of doing it, one is go through the whole program line by line, which is called the interpreter, and changing it into executable form, the other is to convert the whole chunk of the program and convert into executables at once. The program that does that is called compilers. Basic language is a good example of an Interpreter, whereas C uses a compiler.
Why the need of this explanation suddenly? Yes this is very much needed to understand the actual flow of data and instructions in a C# program, as they are common between all languages and apply to C# too. Java achieved its platform independence by utilizing the power of both interpreter and compiler. A Java program is compiled and an intermediate code is generated which can be utilized by any operating system to interpret and execute.
Note: Programming languages produce the executable file (a file that the computers internal organization can understand and execute), and the underlying operating system is responsible for its proper execution. The operating system faithfully executes what the executable contains, and hence bugs and mistakes occur only during our programming. Take a note of that.
[edit] Welcome to C#
Although Java could successfully be a platform independent language, it could not address the problem of cross-language interoperability. What is that? It’s nothing but the ability of the code produced by one language to be used by another language. What is the need of such a feature in a language? Simply because, to produce a very large and distributed software systems it’s a requirement that each and every component combines the potential of all the necessary languages and seamlessly integrates together with each other smoothly executing in almost any environment (operating system).
Also Java could not provide full integration with the Microsoft Windows platform as they are not closely coupled and Microsoft Windows is by large the most popular and used operating system around the globe. Microsoft helped themselves of this issue by developing “C#” which was part of the .Net strategy of Microsoft. Due to the fact that C# is based on the three most favored languages of all times, C, C++, and Java, C# gives a solid foundation to all users and a seamless migration from any of the three languages. Note that, C# is not descended from Java and but they both share a common line of evolution.
C# has many innovative features; chief among them is that built-in support for software components as it was originally designed to be a component-oriented language and has integral support for producing software components.
[edit] .NET Framework
When we talk about C#, it’s inevitable that we mention about .Net framework and how C# is related to it. C# is the language developed to create code for the .Net framework and the .Net framework contains all the libraries ( program components which are loaded on demand, more on this will come ahead in further chapters) for the execution of programs coded in C#. The .Net framework is an environment specifically developed for the development and execution of highly distributed and component based application. It enables different programming languages to work together and provides features like, security, program portability and common programming model for the Microsoft Windows platform.
Essentially the .Net framework consists of four parts namely:
- Common Language Runtime Environment
- Class libraries
- Programming Languages (C++, C#, VB.NET, JSCRIPT.NET)
- ASP.NET
The .Net framework was designed with three major goals in mind, making Microsoft Windows applications more reliable, by providing it a greater amount of security, to give Web based applications and services the flexibility to run both in the traditional and mobile environments and last but not the least a common set of libraries that could be used by all the programming languages, providing cross-language compatibility.
Today’s internet is fuelled by what are called web services, which simply put is nothing but the web site interacting with programs than just users. They take in a request as formatted XML, may perform some actions and return the response to the program as an XML message. And .NET framework was designed to provide programmers already pre-built libraries to develop large scale and complicated web services leaving the nitty-gritty details of repeated and basic functions to be performed by the library and concentrate on the more essential development of the service itself.
Apart from the internet, .NET framework also provides libraries to develop traditional desktop applications for the Microsoft Windows platform, based on what are called Windows Forms(Visual Studio 6 programmers would know about Forms in Visual Basic), which are a combination of VB6 Forms and object oriented concepts of VC++6. In C# all Windows Forms are object-oriented and class based.
[edit] Common Runtime Language (CLR)
As explained earlier, each language consists of a compiler or an interpreter and a runtime environment. The executable code that could be executed by any user is produced by the compiler and the runtime environment provides a set of operating system services to execute your code. The runtime environment is used to separate off the essential services for the execution of the code, from the code itself, to enable the programmer to concentrate on the code rather than these underlying details providing a time-efficient environment for the programmer. Some examples of such services are memory management and memory I/O. .NET framework was designed with this in mind, to provide with a common runtime environment for all its programming languages as each separate programming language came with its own runtime environment, like Visual Basic came with MSVBVM60.DLL, and these runtime environments provided for only a single programming language. Hence some features of Visual Basic are pitifully not available to Visual C++ and the reverse is also same.
As programmers struggled to implement some inherent constructs of Visual C++ into Visual Basic or vice-versa, there were bound to be lots of anomalies and bugs creeping up without the knowledge of the programmer, and are very hard to find them. To ease this pain of interoperability, .NET framework was developed for that very purpose. It provided a common runtime environment by unifying the various runtime engines so that all developers working on different programming languages can harness the power of the other language. The .NET solution for this called Common Language Runtime Environment or CLR for short. CLR provides many services to the programmer, memory management, security, and robust error-handling. CLR also provides cross-language interoperability like memory allocated by one program can be used by the other language.
[edit] Microsoft Intermediate Language
The CLR is responsible for the execution of the .NET code, and it works like this, a C# program is compiled into an intermediate format which contains a special type of pseudocode called Microsoft Intermediate Language (MSIL). MSIL essentially defines a set of portable instructions, and by portable we mean instructions that are independent of any specific CPU, in short a portable assembly language. Although MSIL is analogues to Java’s bytecode, but both are totally different technologies.
Now CLR translates the intermediate code (MSIL) into executable code when a program is run. Thus a program is compiled to MSIL which can be run in any environment for which the CLR is implemented. Microsoft Intermediate Language is in turn converted into executable code using a Just In Time Compiler (JIT compiler). The JIT is activated by the CLR and JIT converts the MSIL into native code on demand basis of the program. Thus a C# program written in a high level language is run as a native code and runs as fast as a native code. And thus portability is achieved.
With MSIL another output also is produced by the C# compiler, called the metadata. Metadata describes all the data used by your program and enables your code to interact with other code and is contained in the same MSIL file.
[edit] C# Managed Code
In general any code written in C# is a managed code and is executed under the control of Common Language Runtime. As described in the previous section any C# program is under the constraint that the compiler produces a MSIL file specifically targeted to the CLR and uses the .NET framework libraries. Managed Code has its own benefits like, modern memory management, cross-language interoperability, security, and support for version control.
[edit] Garbage Collection
Any object oriented language provides the feature of dynamic memory allocation of objects, from a pool of free memory. A major problem that stares us in the face of such a provision is that, memory is limited and free memory gets exhausted way too soon. And hence to address this problem, the language provides a way of recovering the free memory from unused objects, and makes that memory available for subsequent memory requests and reallocation. Another major problem arises when the developer has to manually free this memory, as the developer can accidentally release the memory used by a persistent object making the execution of the code stop abruptly.
C# uses a more trouble free approach called: garbage collection. This system reclaims objects automatically – occurring transparently, behind the scenes, without any programmer intervention. Its working is like, when no references to an object exist, that particular object is considered no longer to be in use, and the memory occupied by the object is released. The recycled memory can be used for a subsequent allocation.
Since the utility of an object cannot be determined during runtime, and the whole memory reallocation also requires lot of time, C# garbage allocation system doesn’t occur periodically but in a sporadic fashion, making it highly unpredictable.
All these above topics will be discussed more as we advance in our concepts and this small introduction is to trigger the inquisitive to flip through these pages and read more about the systems in place in the world of C#. Let us move on to Object Oriented Programming, its characteristics and features now.
[edit] Overview of Object Oriented Programming
C# is largely based on the Object Oriented Programming (OOP) concept and hence a general understanding of the concept will enable you to write C# programs effortlessly and maintain accuracy at the same time. Therefore a general discussion on Object Oriented Programming Concept is inevitable before we even start programming C#.
All computer programs are made up of a set of instructions and the set of data on which the instructions are going to work. Hence by this we can easily then make our programs either, more instruction oriented or data oriented. In the early days, i.e., prior to OOP, all programs were woven around the code and the code was given utmost importance. But when large distributed systems were built there raised a need for maintaining the data on which the code was acting on a distributed environment or in large central storage facilities. This made the data more vulnerable to outside influences, and for data critical applications it became a basic necessity that the data is protected. Hence the programming paradigm shifted from code centric to data centric and hence OOP was born. OOP organizes the code to a key principle that “access to the code is controlled by the data”, i.e., here one has to define the data and the code that has access to the data together.
The discussion of OOP concepts cannot just end without mentioning the three most important features of OO related to C#, they are:
- Encapsulation: This feature enables the programmer to bind the data and the code together into a single piece and thus protecting both from outside influence. Hence a black box of code and data is created which is self contained. An instance of such a black box is called an object. The basic unit of encapsulation in C# is the class. With a class construct you can declare both the data and the code that manipulates the data in a single block. The code and data that form the class are called the members of the class. A C# method is called a function.
- Polymorphism: This feature is incorporated into C# to enable the code reusability (another important feature of OOP) in the level of methods. Methods can be declared in the general sense and they have access to all the classes they are implemented in. (Don’t worry about if you don’t understand it here, we would elaborate on this when we learn about interfaces in subsequent chapters).
- Inheritance: This feature enables a class property to have access to other class properties in the same program code. This is another way of saying a hierarchical classification of data, where the child class can inherit and have access to the properties of its parent class. These come especially handy when more than one class needs to manipulate upon the properties of a single base class. We would learn more about this in subsequent chapters.
With the above OOP concepts at the back of our mind (as these are highly useful when we start dealing with classes and objects in subsequent chapters), let us step into the Visual C# 2005 Express IDE for a walk through of what’s where and write our first sample program.
[edit] Visual C # 2005 Express Editions
All the Microsoft Visual Studio 2005 express editions were designed to focus on productivity, hiding and taking care of the underlaying details and helping the developer to concentrate more on the implementation logic. Just like other versions of Visual Studio, Express edition is also a Rapid Application Development (RAD) tool as their function is geared towards productivity. Visual C# 2005 express edition is easy to use, easy to learn, and streamlined, and relatively simpler than other higher-end versions of Visual Studio as the full breadth of features are not included, making the learning curve less steep and fit the needs of even non professional developers.
The Visual C# 2005 is developed with the beginner programmers in mind, people who are curious about programming, and who are looking an easy way to build windows applications, while learning how to program. It is the ideal tool to rapidly develop day to day applications and have fun while learning it.
Applications that can be built:
With the Visual C# 2005 Express Edition you can build the following kinds of applications:
- Windows Applications: Applications that have graphical interface with buttons, windows, menus, toolbars and so on.
- Console Applications: Applications that have no graphical interface and simply use text to communicate with the user. (These are the kind of applications we would be developing for a large part of the book as it makes the learning easy and effective).
- Reusable Components: A group of tools helpful to build other applications.
What we won’t be able to develop are Web Services, and Web Sites and we have the Microsoft Visual Web Developer Express Edition for the purpose.
[edit] Advantages VS Disadvantages of C#
Advantages:
- C# borrows concepts from Java and C++, adopting only the good bits from those languages and eliminating overly confusing and error prone features, which are the major sources of bugs in a code.
- C# is a terse language.It’s very tiny even with the commands.Visual Basic on the other hand has a command for almost any kind of situation that the developer may face during the development of the code making its reference a real hefty one.
- C# supports effective and reusable components.
- C# is portable at the same time it is cross language compatible for all Microsoft Windows based languages and programs specifically targeted to that particular platform can be coded to interoperate with the code of other languages.
- C# implements the modern programming concept of Object Oriented Programming which enables the developer to produce secure data centric applications and take the user to the next level of experience.
- C# programs can be written in as simple as a textpad and a command line which are common to any operating system provided the developer has installed the CLR and the framework priorly. Microsoft’s Rapid Application Development Suite products, named Microsoft Visual Studio ships with a separate Visual tool for C#, and gives developers visually rich tools for development and deployment.
- C# RAD tools gives the developer the power to produce “One click install” application, where the user needs no prior software experience and can install and use C# applications like any other windows program.
- C# provides the ability of code extension to the developer with which developers can produce extensions and wrappers to use the underlying library to behave the way the developer want it to.
- C# programs are managed code, to say, they are coded and executed in a controlled environment leaving little room for anamolies called “bugs” to creep in. Also it has eliminated some of the “unsafe” features of C++, which can provide intruders to breach secure C# programs.
- Due to their high portability, they are used for web programming and with new information sharing concepts like web services, they bring distributed information sharing to the very desktop of the user and all that the user needs is a computer and a browser.
- C# hides low level details from the application developer and provides with a wide range of library functions which a developer can utilize to produce code for almost any kind of application and focus on the logic of the application and need not bother about its compatibility with other windows machines.
- C# can be used to write wide range of applications due to their portability, from simple desktop widgets to high end web services, secure systems programming and even robotics.
Disadvantages:
- All though portability is what with C# was developed, C# programs are largely for Microsoft Windows Environment which although happens to be the most widely used Operating system over the globe, but with Open Source technologies, especially platforms like Linux catching up, C# still has to long way to go. This is one major shortcoming of C#.
- C# has eliminated the “unsafe” code functionalities from C++ (from which it was devloped); it has its own set of functionalities which are to be used with caution by the user. More of this will be discussed further on in the book.
- Although C# programs can be written as little as a text editor and compiled using command line, it still needs the .NET framework to be present on the system, which cripples down the portability in the development of C# programs by a large amount, and makes it more Microsoft Windows dependent. There’s an alternative version of the .NET framework produced by the FOSS (Free and Open Source Software) community called the “Mono” project which brings C# to the Linux variants.
At last we come to the last section of our introduction by introducing to internet technologies like HTML and SOAP, as the whole idea of .NET framework is based on distributed computing and internet.
HTML=HyperText Markup Language
HTML is primarily a markup language and developed as a subset of Standard Generalized Markup Language (SGML), which is a higher-level markup language that has long been a favorite of the Department of Defense and many other organisations with a truly astounding volume of documents to manage. HTML is much simpler than SGML as it was conceived for the transmission over internet, and is more application-oriented document format. HTML gives the designer the flexibility of creating pages that can be read on any type of computer and on any web browser software which is connected to the internet. HTML pages are so simple that any designer can produce HTML pages without the requirement of any special kind of softwares. HTML is a public standard, and is so simple that one can get all the information he needs through the internet and can produce HTML documents from a scratch.
This forms the formal definition of HTML, the very basic markup language to produce stunningly creative websites that are floating around the web. The next higher up technology that we are going to review is the XML.
XML = eXtensible Markup Language
XML was developed by the World Wide Web Consortium (W3C) XML Working Group and again derived largely from SGML in the year 1996. XML is a widely supported open technology, that is to say, it is non-proprietary technology) for electronic and data exchange and storage. XML is actually a language used to create other markup languages to describe data in a structured manner.
Also XML documents doesn’t contain any formatting information and application that use XML data has to decide how to manipulate or display document’s data.XML also gives flexibility to programmers to create markup for any type of information. This extensibility enables the document author to create entirely new markup languages for describing data such as mathematical formulas, chemical molecular structures, music, news and recipes.XML documents are highly portable and viewing and modifying XML documents doesn’t need any sophisticated softwares. The XML marks the start of a new era of Information Technology where a huge amount of information is transmitted via internet, let it be some pre-historic data, or the latest current news on air, any and all type of data can be stored and distributed via XML files and this forms the basis of our next topic, SOAP.
SOAP=Simple Object Access Protocol
Yes it sounds funny, this technology has enabled free distribution of information across the globe, within just a few clicks.Normally many applications use the internet to transfer data, and some of these applications run on client machines with limited computing powers, and thus requires invoking methods on other computers to process data. And also most applications use proprietory data specifications and protocol and thus straining the inter-application communication of data. With these the applications also reside behind firewalls, which often restrict data communication to and from the application. To address these problems, IBM, Lotus Development Corporation, Microsoft, DevelopMentor, and Userland Software developed the Simple Object Access Protocol (SOAP). SOAP is an XML-based protocol that allows applications to communicate easily over the Internet using XML documents, called SOAP messages.
A SOAP message typically consists of an envelope, which is a structure that describes a method call. A SOAP message’s body contains either a request or a response. A request messages’ body contains a Remote Procedure Call(RPC), which stated in general terms is a request to other machine to perform a task.It specifies the method to be invoked and the parameters the method takes. The application sends a SOAP message using HTTP POST.
Web Services are special type of application built into any websites which enables live sharing of information with its browsers, typically harnesses the power of XML, SOAP, Web Services Description Language (WSDL), and Universal Description, Discovery and Integration (UDDI). XML as we know creates markup language and describe data. SOAP enables data transfer between distributed systems on the internet, WSDL is an XML-based description language, and it describes a web service so that other applications can understand and access the services provided by the web service. UDDI is another XML based format that enables developers and business to publish and locate web services on a network.
Further on, we’ll be learning more about Web Services, and infact we’ll be creating a working service using our own C# which will communicate and correspond to applications over the internet. With this topic we conclude the introduction chapter of our online C# book, and we look forward for you to join us on this exciting journey of C# in the next chapter which will formally introduce basic programming constructs and many many many more things……..
[edit] C# 3.0 Features
C# 3.0 is code named “C# Orcas” and introduces several extensions on C# 2.0, and supports the creation of higher order, functional style class libraries. These extensions enable the development of compositional APIs (Application Programming Interfaces) that have equal power of query languages in domains such as relational databases and XML. These extensions include:
- Local variables are implicitly typed, permitting the expressions which initialize them to determine the type of the local variable.
- Extension methods have been added, making it possible to extend the existing types with additional methods.
- A new set of anonymous methods have been evolved, to provide improved type inferences and conversion to both delegate types and expression trees, and these methods are called Lambda expressions.
- New object intializers have been added for the ease of constructing and intializing new objects.
- New tuple types, which are automatically inferred and created from, object initializers.
- A new form of array creation and initialization, which infers, the element type of the array from an array initializer.
- Query expressions provide language integrated syntax for queries that are similar to relational and hierarchical query languages. (SQL and XQUERY).
- Source: Microsoft Windows C# 3.0 Specs. May 2006.
[edit] What you should already know
Before reading this tutorial you must have the following already mastered.
- Basic computer skills
- Basic math skills (Elementary Algebra recommended)
- A basic understanding of Windows
|