Introducing C# and the .NET Framework

This is the first article in my series (Introducing C# for Developers). You will learn C# in a short time, and you will know what features C# introduces to software development and how rapidly you can develop software applications for the .NET platform.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 100
January 31, 2005
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

I begin the series with an introduction to C# and the .NET Framework. You will learn about the Common Language Runtime, the Common Type System and the Common Language Specifications. Then together we will create your first C# application using C# Compiler, and we will also  create this application using Microsoft Visual Studio.NET. 

After this introduction you will learn more about .NET Types, and the story of Value Types and Reference Types. I know that you are excited to learn about C# classes and how a C# class is encapsulated in one file (unlike C++); this will come with a discussion of C# Access Modifiers. After you master the concepts related to a C# class you will need to learn about controlling the path of the application with the familiar if statement and its friends belonging to the iteration statement family.

Ready to sharpen your skills? It's time to learn about C# methods and how C# methods can make your programming constructions encapsulated. You will learn about method overloading and parameterized methods, and how you can pass parameters by value and by reference. You will also learn about the ref and out keyword, and how they can change the way you design your method's parameters.

After methods come properties. It's very important at this time to learn what a C# compiler generates under the hood when you write properties in your classes. You will learn properties syntax and how to make your properties Read-Only, Write-Only and Read-Write. You will learn what a static property is, too. Then you will learn about the various operators introduced by the C# language and how to use them. C++ defines a construction called Indexed Property, but in C# we call it an Indexer, and it can make your life much easier so a discuss about Indexers is a must as well.

A .NET Application is typically one or more assemblies so you need to learn about assemblies as well as namespaces,  so one article coming up will be about Assemblies and Namespaces. Then we will discuss some advanced C# programming concepts like Inheritance, Polymorphism programming and Interfaces, which take you into some great details about C# programming. Delegates maybe not familiar to you so we will spend some time studying it followed by C# Events. I will end the series with an article about Object manipulation and operations. I hope that this series will sharpen your skills.

The .NET Framework

A Framework is a set of class libraries that provide the developers with the common system functions and services that can be used by a programming language. But the .NET Framework extends this concept. The .NET Framework is a large set of class libraries that can be used for many programming languages, like Microsoft's C#, Visual Basic, Managed C++ and more. So the first thing you notice here is that the .NET Framework class libraries can be used for more than one programming language (we will understand this more when I get to CTS and CLS).

Besides the Class Libraries, the Framework provides a Common Language Runtime (CLR) that manages the execution of any .NET application written in it using a .NET programming language. Simply put, the .NET Framework consists of Class Library that provides the common system services and functions that you will use and extend in your applications, and an Execution Environment that manages .NET Applications. The functionality provided by the Class Library will help you to develop Windows applications, Web applications, distributed applications and even let you integrate XML and XML Web services into your applications.

The .NET Framework Class Library is written by Microsoft and it's very easy to use. For example, if you want to write a line to the console, you will use a method called WriteLine() of the Console class and pass to the method a string that you want to be written to the console. You have classes for almost everything you will need to do, such as: text manipulation, threading manipulation, XML handling, I/O, GUI controls for Windows and Web applications, database access presented as ADO.NET and Enterprise Services functionality.

It's important to note that C# is not part of the .NET Framework. C# is an Object Oriented programming language of its own, and it has its own syntax, control structures and construction building statements. At the same time, it has been created to be used with the .NET Framework, and the C# compiler generates code that runs under the .NET Environment. This code is called Managed code because it's managed by the Common Language Runtime Environment. In other words, Microsoft designed C# to be the core programming language of the .NET platform and to use, leverage and extend the .NET Framework class library.

I know that you now have many questions to ask, such as "How is it that all these programming languages use only one set of class libraries?" and "What is the role of the Common Language Runtime in executing .NET Applications?" We will take it step by step in the next few sections so you can answer this questions by yourself. First let's consider what happen when you compile a C# source file.

C# Source code > MSIL > Native CPU Code

   

When you write an Application in C# the compiler doesn't generate a binary file (like traditional compilers) but rather it generates a file (for now you can call this file a .NET Module) that contains Microsoft Intermediate Language (MSIL) code,  plus metadata (which we will discuss in the article on the Assemblies). So if you use Visual Basic.NET, the VB.NET compiler will generate MSIL, too -- and this is also the case for Managed C++ or any other .NET compliant language (more about .NET Compliant Languages later).

The Common Language Runtime (which is the execution environment for the .NET Framework Applications) has a compiler called Just-In-Time, or the JIT Compiler, which will compile the MSIL Instructions into native CPU Instructions upon the first execution of your application methods on a one-by-one basis. I think this needs a little more explanation.

When you write a C# application that contains only two methods, such as the following class:

class Class1
{
    static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
            Console.WriteLine("I like C# Programming");
        }
}

then, when you compile this code, the C# Compiler will generate a file that contains the MSIL of the application. When you execute this application the Common Language Runtime will compile the MSIL Instructions into native CPU Instructions using the JIT Compiler on the first invocation for each method in your program.

So for the first call to Console.WriteLine("Hello World"); method will call the JIT Compiler to compile it to native CPU and save this native CPU version of the method to a block of memory, so the next call to this method will call this memory version, which guarantees fast performance.

The next statement calls the same method (Console.WriteLine()) with a different argument, so this will call the native CPU in-memory version of the method and pass it the string "I Like C# Programming." Note that when you terminate the execution of your application the in-memory version of your methods will not be available (it will be destroyed) and it will be created each time you execute your application. So the process is repeated every time you execute your application.

You may think that this two step compilation may slow the performance of your applications, but you should know that Microsoft spent a lot of time on optimizing this process. Before .NET, when you compiled an application, the compiler optimized the code but it optimized this code on the machine that you used to compile the application. So when you installed or deployed the application on your client machines, it would simply run but it would not be optimized. With the .NET Framework and the Common language Runtime, the application is compiled to MSIL Instructions, and when you run the application the JIT Compiler will optimize it depending on the current platform. So when you use, for example, a computer with a Pentium 4 processor, the JIT Compiler will know and actually optimize to this processor's features.

The .NET Type Story

When you program in .NET you will define types. For example, when you define a class or a structure in C# you actually define a type of a value. Take a look at this Employee class:

class Employee
{
    public string Name;
    public int Age;

    public string GetPosition()
        {
            //operations to get the position of the employee
            return position;
        }
}

Note: I will not explain the members of the Employee class for now but it's enough to say that this class contains two fields and one method to get the employee position.

So a Type is a representation of some values. For our Employee class example we define a type of class (Employee class) that stores one string value for the Name field and one integer value for the Age field. But we've only gone halfway, because .NET Types define a value and its associated operations.

For our example the GetPosition() method is an operation defined on the Employee class to return an Employee position. Let's take one of the .NET built in Types as an example: Int32 Type stores 4-byte integer values. C# is a type safe language, which means that if the Employee class has only two fields of type string and int then you can't store any other values in an instance of that class type. Nor can you store a string in the Age field and an integer in the Name field.

C# is also a strongly-typed language. That means if you declare a variable of type Employee then you will store (or reference) an instance of type Employee or an instance of a class that derives from Employee (more on that in a later article). Type-Safety and the Strong-Type mechanism is implied by the Common Language Runtime (CLR) at Runtime and by the C# Compiler at Design Time. You can think of this operation in a simple way: the CLR knows exactly what to do when you declare a variable of a certain type (in our example the Employee type) and also the CLR knows what are the values and operations defined in this type. So you can't write a statement that stores the character string "Michael" in a field named FirstName of an instance of the Employee class type like the following statement:

anEmployee.FirstName = "Michael";

The Compiler will generate this error

'Employee' does not contain a definition for 'FirstName'

because there is no such field defined in the class Employee. This is happening because, when you define a type (in a form of a class, structure, enumeration or anything else), the C# Compiler will emit MSIL for that type, along with metadata which tells the CLR what the type is all about. In other words the metadata introduce the Type to the Runtime and contain all the information needed at Runtime, and the CLR uses these information extensively. Some Development Environments, such as Visual Studio.NET use the metadata to express some features, such as Visual Studio IntelliSense feature.

A World of .NET

You will find this expression a lot in my articles. Microsoft realized that, if their .NET Technology is exclusive only to Microsoft, then .NET will not make such an impact in the world of software development. But the folks at Microsoft are very clever. Microsoft submitted large parts of the .NET Technology to the EMCA to become EMCA standards. Microsoft has submitted the C# Specifications, the Microsoft Intermediate Language Specifications, the Metadata, and a large part of the FCL (.NET Framework Class Library).

Think about it. Now vendors who design compilers, programming languages and development tools can use these specifications to create compilers for their own languages to integrate with the .NET Technology, and the benefits are huge. As you know, each programming language has its own syntax, control structures and building block mechanisms, and this gives each programming language its own set of features and drawbacks. For example, C# is a very appropriate language for I/O, and APL is very appropriate for mathematical calculations. If you are able to use both languages to develop one application, it would be a great feature and a big move in software development.

This is now possible because compiler designers can use the .NET Specifications and write compilers for their programming languages to produce Microsoft Intermediate Language (MSIL) code that's managed by the runtime. Now you can use Visual Basic, C#, Managed C++ and APL in one application, and use the features of all of these programming languages. In short, .NET brings a lot of possibilities to software development. The expression "a .NET Complaint Programming Language" is very important to understand. If the language has a compiler that produces MSIL, then it's a .NET Compliant Language, and we will see how this is possible through the use of CTS and CLS standards.

The Common Language Runtime

The concept of the Runtime Environment is not new. Developers used to programming using Microsoft Foundation Classes (MFC) know that a runtime environment is needed to manage their applications. Java also has a runtime environment (the Java Virtual Machine), but C#, Visual Basic.NET, Managed C++ and all the other Microsoft.NET Compliant Languages have only one runtime environment between them, which is the Common Language Runtime. The CLR is the part of the .NET Framework that executes and manages any .NET Application, and as you know, the code produced by all .NET Compliant languages is MSIL and it's called managed code.

The CLR understands only MSIL (not C#, not Visual Basic.NET) so whatever the language has been used to produce the MSIL Instructions is not an issue for the CLR. The Interesting thing about the CLR is that it's loaded automatically each time you execute a .NET application, and it's represented as an assembly file (an assembly is a unit of deployment in .NET) called mscoree.dll (stands for Microsoft Common Object Execution Engine). It is needed on the machines that will run a .NET application, so you need to make certain your clients have the CLR installed. You can install it using the .NET Framework distribution components.

I like to think of the CLR as a monitor, guard and a supervisor for all .NET Applications. I say that because it's responsible for:

  • Compiling the MSIL instructions to native CPU instructions. As you know, .NET language's compilers produce files that contain MSIL code, and for execution of your application the CLR uses its JIT Compiler to compile the MSIL Instructions to native CPU instructions, and to optimize these instructions to utilize the process features.

  • Managing memory automatically for your applications using a Garbage Collection mechanism. This guarantees that objects that have no reference in your application will be freed, and you as the developer will not worry about releasing memory for objects. This guarantees faster performance and, at the same time, gives you the time to focus on the development issues of your applications.

  • Handling application errors when required by throwing an Exception.

  • Guaranteeing that your .NET Applications will run in a safe context by using a mechanism called Code-Access Security. There is another security mechanism called Role-Based Security which controls the access to system recourses. Using .NET Security that is managed by the CLR, you can develop very secure applications.

  • Knowing what files are needed to execute your application (these are the assemblies that represent the .NET Framework Class Library). It uses an algorithm to search for these files. The simplest C# program must refer to and use one assembly that contains most of the basic functionality, such as methods to write and read lines from and to the Console.

  • Beginning a process called Code Verification. When the JIT Compiler begins to compile the MSIL Instructions to native CPU Instructions, this process checks type safety. In other words it ensures that your code doesn't make any illegal operations or allow any illegal access, and this is where the expression that "C# is a Type-Safe Language" comes from.

The Common Type System

When Microsoft designed the .NET technology, they wanted to invent a technology that would last for some time with great stability and interoperability. When you think about most programming languages,  you will find that a particular programming language consists of a set of keywords associated with a specific syntax. Attached to it are a group of data types like integer numbers, strings and floating point numbers. Most programming languages offer these data types, and most of them use the concepts of encapsulating the code into methods and, as a result, into classes.

This is good, but because each language defines its own data types and its own syntax, it's difficult to use a component written in another language in your code, although COM gave us this feature to some extent. You could write a COM Component in Visual Basic and use it from a scripting language like VB Script, but you can't unify the way all programming languages use each others' components -- for example, you can't create a COM Component in C++ and make use of it in a Visual Basic program.

The solution to this problem involves separating the implementation of most of the popular programming languages' data types into a unified system of syntax that can be used to operate on these data types. Microsoft has designed a Common Type System (or CTS) that defines most of the data types that have been used by most popular programming languages. The Common Type System doesn't define the syntax that programming languages use, nor does it define the keywords; it just defines the Common Data Types for all the languages that will be managed by the .NET CLR Environment.

Different languages may use a subset of the CTS called the Common Language Specifications (or CLS) to comply with the .NET Framework (we will discuss the CLS in the next section). The most important thing that you need to understand is that the CTS doesn't define any syntax, and it's the part of the programming language to define it. I think that by now you need a definition for the CTS.

The Common Type System: The CTS defines the rules for Types that run and can be managed by the Common Language Runtime for compilers and programming languages designers, so they can develop compilers to utilize these types and thus produce MSIL code that can be run under the CLR.

If you ever code in C# you may ask yourself what data type to use --the ones introduced by the C# Language or the set introduced by the CTS? The answer is very simple. .NET programming languages expose their data types (that's a subset of the CTS) in their own way. For example, the CTS defines a 4-byte Type, Int32, that stores integer numbers from negative 2,147,483,648 through positive 2,147,483,647. In C# you can use the int keyword instead of the CTS official name System.Int32 to declare a variable of that type. Actually you can use any of these techniques, but for consistency it is best to use one technique throughout your code. Personally I use the C# aliases. The table below lists the CTS built-in types and their C# aliases keywords.

DescriptionC# Keyword

CTS Type

The base class for all class in the .NETobjectSystem.Object
Signed 4 bytesintSystem.Int32
Unsigned 4 bytesuintSystem.UInt32
Signed 2 bytesshortSystem.Int16
unsigned 2 bytesushortSystem.UInt16
a character string valuestringSystem.String
Signed 1 bytebyteSystem.Byte
Unsigned 1 bytesbyteSystem.Sbyte
Signed 8 byteslongSystem.Int64
Unsigned 8 bytesulongSystem.UInt64
Two bytes Unicode charactercharSystem.Char
four bytes floatFloatSystem.Single
eight bytes floatdoubleSystem.Double
sixteen bytes types exact to 29 digits. It's a requirement for banking and financial applicationsdecimalSystem.Decimal
Boolean value, true or false boolSystem.Bolean

A full discussion about types will have to wait until the next article. In that article, I will talk about why understanding types is critical for understanding C#. We will discuss Value Types and Reference Types and their mapping to the Common Type System. Value Types such as Built-In and Structures,  and Reference Types such as Classes, Interfaces, Delegates, Arrays and Strings will be discussed then as well.

A World of Interoperability Through the CLS

Since each programming language has its own features and drawbacks, the ability to use more than one programming language in your applications can make our life easier as programmers. Remember our example about using C# for the part of your application that needs I/O and using APL for the part that needs complex mathematical calculations? Unless both languages expose the same data types with the same mechanism, they cannot interoperate. Add to this that Microsoft wanted developers to be able to have the code written in one language used in other languages, and you'll find that you can write a class in Managed C++ and derive from it in C#, and so on.

All this is possible with the Common Type System, but the CTS is huge, and there is no one programming language that supports all the types that exist in the CTS; different languages may expose different types. But all languages require the Boolean data type, the integer data type, the floating point data types and a character string data type. In other words, these data types are the core for any programming language today.

Microsoft's solution is the Common Language Specifications (or the CLS). The CLS is a large subset of the data types and rules of the CTS defined for compilers and language designers. It explains what is necessary in order to implement a .NET Compliant Language that can interoperate with other .NET programming languages and third-party .NET Components. If you are designing a compiler for your language to be managed by the runtime, and to use the .NET Framework Class Library, you need to implement at least the CLS specifications to make your programming language integrate with the .NET world through the CLS. Think of the CLS as the minimum set of functionality and data types that any .NET compliant language will support, and that's exactly how these languages interoperate, through the CLS implementation.

Also note that almost all the classes in the .NET Framework Class Libraries (FCL) are CLS-complaint. You will be able to use these classes from any .NET Compliant language. Actually the expression ".NET Framework" indicates a large set of classes that can be used from any .NET Compliant language. There are some classes and structures in the FCL that are not CLS-Compliant, like uint and ulong data types. Also note that third parties ensure that their .NET Components are CLS-Compliant, so they can be used from any .NET Compliant language like C#, VB.NET, Managed C++ and more than 20 other .NET Compliant languages from many of vendors.

The C# Compiler can help you to check for CLS Compatibility through the use of the next attribute:

[assembly: System.CLSCompliant(true)]

You need to put this line outside your namespace or any class declaration. If you are using Visual Studio.NET, you need to put this line in the AssemblyInfo.cs class. It indicates that you are developing a component that can be used from other .NET Compliant languages. The C# Compiler will issue warning when it finds any violation to the rules of the CLS.

For example, C# is a case sensitive language, and you can define two public fields as DotNet and dotnet; C# will understand that they represent two different fields, but with a non-case sensitive language such as Visual Basic.NET will cause the compiler to issue an error if you try to use DotNet and dotnet as identifiers for two separate fields. If you developed a class that contains these two public fields, how do you use this class in a VB.NET program? You can't; you must check your work using the System.CLSCompliant(true) attribute. The C# Compiler will issue a warning to tell you that your class is not CLS-Compliant; thus you will need to change the names of your public fields.

Note that the CLS Compliance mechanism applies only to the public interface of your classes. The internal implementation is not an issue; the C# compiler will not issue a warning if you use two local variables in a method (X and x) because it's internal to the method.

Some of the CLS Rules imply that, if you want to define a CLS-Compliant class, you must inherit a CLS-Compliant class. They also imply that, when you declare an Array Type, the element type must be a CLS-Compliant type, and the Array index must be zero-based (so all the .NET Compliant languages use the same mechanism). Case sensitivity is an issue to the members of CLS-compliant types to avoid using the same identifier with a different casing.

If you have Microsoft Visual Studio .NET 2003 installed on your computer, and you want to read more about the Rules of the CLS and the Specifications, I advice you to navigate to the folder on your hard drive labeled: \Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Tool Developers Guide\docs and take a look at Partitions I, II and maybe III of the specifications. 

We will create your first C# Program (the familiar "Hello World" example) with the C# compiler, then with Visual Studio.NET, so you can imagine how Visual Studio.NET can save you a great deal of time developing C# and .NET applications. We will create a Console-Based application to represent our Hello World example, so let's begin.

Where Can I Find the .NET SDK?

In order to be able to develop C# applications you need to download the .NET Framework Software Development Kit (SDK) from Microsoft's website:

http://msdn.microsoft.com/library/default.asp?url=/downloads/list/netdevframework.asp

You will find in this SDK:

  • The C# Compiler represented as csc.exe
  • Many utility tools
  • SDK Documentation and a lot of examples

You need to install the .NET Redistributable package to be able to run .NET applications. It contains the .NET Runtime and other components that are needed for running .NET applications. The Redistributable package can run on Windows 98, Windows Me, Windows 2000, Windows XP, Windows 2003 and Windows NT. In order to develop .NET applications, of course, you need to install the SDK and you're on the way to doing that now.

Note: I use Visual Studio.NET in all the code examples as it's the primary tool for developing C# and .NET Applications. You are free to use the SDK and the C# compiler but VS.NET saves a lot of time and provides a ton of features.

Configure the Path Environment

The C# compiler lives in the folder C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322, and there are some tools that we will need that live in the folder C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin, so we need to modify the path Environment Variable to refer (search in these folders) for the tools that we will be using. Thus we can compile C# applications anywhere on the hard disk, because the command-prompt will search these folders for the tools that we need if it can't find them in the current folder.

Note: I assume that you are using Windows XP.

Right click on My Computer and select Properties --> Advanced --> Environment Variables and you will get to the next windows.

Introducing C# and the .NET Framework

In the System variables section locate the Path variable and click Edit, and the Edit System Variable Window will be shown

Introducing C# and the .NET Framework

We need to add the following two folders that contains the C# Compiler and other .NET tools:

C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322
C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin

To add these folders you need to append a semicolon (;) to the end of the variable value and separate each folder location with another semicolon. Add the folders and click on OK three times. And now you are ready to compile C# applications!

Writing the Hello World Example with the C# Compiler

Open your favorite text editor (I'm using notepad in this example) and copy the following C# code into the file. Save it as Hello.cs. The cs extension stands for C Sharp.

using System;

namespace FirstApplcation
{
  
   class Class1
   {
      static void Main()
      {
         //the Console.WriteLine() method takes a string as
         // a parameter and write it to the console
         Console.WriteLine("Hello World, I like C#");
      }
   }
}

You need to compile the Hello.cs file using the C# compiler with the following command from the command prompt:

csc Hello.cs

The C# compiler will compile the application and you would see the version of the compiler in the command prompt. This means that everything is fine. Run the application using the command prompt and you will get the following message: "Hello World, I like C#."

Writing the Hello World example with VS.NET

Now we will create the Hello World example using Visual Studio.NET (VS.NET) so you can see the power of VS.NET and its IDE (Integrated Development Environment).

Start VS.NET and select File --> New --> Project. The New Project windows will be shown. Choose Visual C# Projects from the Project Types pane and choose Console Application from the Templates pane.

Introducing C# and the .NET Framework

Notice that Visual Studio.NET automatically save the project files under

C:\Documents and Settings\Michael\My Documents\Visual Studio Projects

where Michael is the current user that I logged in with. Under the Visual Studio Projects Folder you will find a folder named FirstApplication (as the name that we will select for the Project). Write FirstApplication in the Name textbox and click on OK. VS.NET will create the needed files to create the project for you. Open the Solution Explorer (if it's not already opened) using the combination CTRL + ALT + L , and you will find some files created automatically for you. Since this is not an article about VS.NET, I will not go into further details about this tool.

Here's the automatically generated C# code that lives in the only generated C# class file which always called Class1.cs:

using System;

namespace FirstApplication
{
   ///
   /// Summary description for Class1.
   ///
   class Class1
   {
      ///
      /// The main entry point for the application.
      ///
      [STAThread]
      static void Main(string[] args)
      {
         //
         // TODO: Add code to start application here
         //
      }
   }
}


 
VS.NET is a smart development environment; it generates a lot of code on your behalf, especially if you are working with Windows-based applications and Web-based applications. When you add a button to the form and double-click on the button to write an event handling code, VS.NET will generate an event handler method and register it with the event delegate (it's the .NET mechanism to fire event which we will spend some time on). Because Console-based applications have a limited functionality, VS.NET generates only a class with some comments, along with the Entry Point of the application.

Delete the comment inside the Main() method and add this line of code:

Console.WriteLine("Hello World, I like C#");

While you type the above line of code, VS.NET Intellisense's feature offers you a way to expose all the available Console class members. This feature makes our development easier, because we get a list of all the available members for a certain type.

We will not invoke the C# compiler to compile the application; we will just click the Debug --> Start Without Debugging menu option or press the CTRL + F5, and VS.NET will compile the application and save it under the bin\Debug folder inside the application folder (which in this case is FirstApplication). The application will automatically execute, and you will get the same message "Hello World, I like C#" as you did in the compiler version, with one difference. We started the compilation process without going into debug mode, so when the message outputs to the Command Prompt, the application will terminate and we will not be able to see it. We can modify the code to wait until we press the Enter key, then terminate. Add the following line of code

Console.ReadLine();

This line of code will force the Command prompt to wait until it reads a line (in this case we will press the enter key only) and then terminate. This time run the application using the F5 key only; it will compile and run as expected. You will get the message "Hello World, I like C#" and the Command Prompt will wait until you press the enter key, then terminate the execution.

Although we will have a complete article about .NET Assemblies and Namespaces later in this series, you need to know what they are before we analyze the program code.

Assemblies

Every time you compile C# code the file produced (.dll file or .exe file) is called an Assembly. The Assembly is a self-describing component; when you compile the source code files the compiler emits information about the types contained in the application, along with other information that is needed by the runtime (such as what files are needed to run the application). The Assembly is a logical group of one or more files, so you can have one assembly represented as MyAssembly.dll file, and you can have another assembly that consists of more than one file (or module).

The term "logical group of files" may be confusing for some of you. VS.NET generates a single-file assembly, which means that all the C# source code files will be compiled in one file with an extension .dll or .exe, which is the assembly of the application. The C# Compiler will emit information to tell the assembly that all the program types' definitions are grouped in this file, and that produces a single file assembly.

If you need to create a multi-file assembly, then you must use the C# Compiler to produce your program as modules and link these modules together using the C# compiler switches. Only one file in the assembly will contain information about the other parts (modules) of the assembly; that's why we call it assembly, because it is a group of one or more files linked together. You may want to produce a multi-file assembly if there are some parts of your program that will be rarely used, so it may be downloaded from the Internet only when needed. You will learn how to produce a multi-file assembly in an upcoming article (".NET Assemblies and Namespaces").

Namespaces

Suppose you have a class named Employee that represents an employee in the HR department. In the system there's another Employee class that represents an employee in the IT department. You want to define these classes, so the first thing that come to your mind is, how I can differentiate these separate entities? The answer is "use a namespace."

A namespace is just a logical organizing of your types to avoid name collision and to effectively organize your application's classes and other types. The .NET Framework uses namespaces to organize its class libraries. For example, the System namespace contains basic data types like Int32 and Int64. It also contains namespaces such as System.IO and System.Text. It's very easy to nest namespaces. Let's see the code for the Employee classes: 

namespace HR
{
   class Employee
   {
      // class functionality and code goes here
   }
}

namespace IT
{
   class Employee
   {
      // class functionality and code goes here
   }
}

As you can see, the namespace HR contains a class called Employee which we can call using the form namespace.classname, HR.Employee. The IT namespace contains another class called Employee which we can refer to as IT.Employee. The next code can instantiate an object of each class with no problems:

// creating an instance of the HR.Employee class
HR.Employee emp = new HR.Employee();
// creating an instance of the IT.Employee class
IT.Employee emp2 = new IT.Employee();

A namespace declaration consists of the keyword namespace followed by an identifier for the namespace. You can nest namespaces as much as you want, but please avoid creating a long hierarchy of namespaces. Microsoft recommends a pattern for using namespaces:

CompanyName.ApplicationName.ComponentName

We can represent this pattern in the following namespace declarations:

namespace Microsoft
{
   //classes that relate to this namespace goes here
   class BasicFunctionality
   {
   }

   //nested namespaces goes here
   namespace Office
   {
      //classes that relate to this namespace goes here
      class BasicFunctionality
      {
      }

      //nested namespaces goes here
      namespace Word
      {
         //Word classes goes here
      }
   }
}

We can create the same structure using a slightly different syntax (which is acceptable if you want to create these nested namespaces across multiple files):

namespace Microsoft
{
   //classes that relate to this namespace goes here
   class BasicFunctionality
   {
   }
}

namespace Microsoft.Office
{
   //classes that relate to this namespace goes here
   class BasicFunctionality
   {
   }
}

namespace Microsoft.Office.Word
{
   //classes that relate to this namespace goes here
   class BasicFunctionality
   {
   }
}

Now you can create each namespace in one C# source code file and they will be nested.

Analyzing the Code

Now let's analyze the code that we have written in our "Hello World" example.

1- using System;

This line simply tell the C# compiler to use the classes that live inside the namespace System, so instead of writing fully qualified names like System.Console.WriteLine() we can write Console.WriteLine(). All C# programs use the System namespace because it contains basic functionality such as writing to the console and, as we said before, it contains the basic data types of many other basic structures that are needed by every C# program.

2-  namespace FirstApplication{}

This is a namespace declaration that we will define our class within.

3- class Class1{}

This is a C# class declaration. Classes in C# are mobile code; in other words, when you define a class in C# you define all the members in the same class file.

4- static void Main()

This is the definition for the Main() method, which is the entry point of Console-based or Windows-based C# applications. Note that VS.NET generates another version of the Main method, but I don't want to go into the details in these article. For now it is enough to say that the Main method must be static, which means that you don't have to instantiate an object of the class in order to call the method.

Inside the Main method we call the static method WriteLine of the class Console which takes as a paramter a character string to write it to the console.

Note: We used the using System; statement so we can write the statement Console.WriteLine() instead of System.Console.WriteLine.

I hope you've found this article helpful in understanding C# and the .NET Framework. 

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials