Visual CSharp .NET Developer's Handbook (2002) [eng]
.pdf
Reduced complexity Developers need to remember too many arcane facts right now. For example, data conversions can become a major source of problems for any developer. Because C# is a true object-oriented language, elements such as variables are treated like objects in most cases-especially during data conversion. This means you can use methods like ToString(), Convert(), and Parse() to convert between data types, even for data normally treated as values. The developer doesn't need to worry about memory management as much, since the Garbage Collector automatically frees memory used by variables. C# variables are also type safe and automatically initialized. In short, Microsoft looked for common development errors and attempted to find ways to resolve them. Accomplishing this goal makes C# more accessible to developers than a language like C++.
Note We'll discuss the Garbage Collector several times in the book. The Garbage Collector provides the memory management features found in .NET. Whenever the Garbage Collector runs, it looks for and frees unused objects and resources. The Garbage Collector is one tool that .NET uses to reduce application errors, especially those related to memory.
Web standard support Not every application created today will interact with the Internet, but a lot of them do. While you can use existing languages to create applications that will work on the Internet, most don't provide full support for web standards like eXtensible Markup Language (XML) and Simple Object Access Protocol (SOAP). The lack of web standards support makes applications run poorly, introduces security problems, or creates other hazards. Web support comes in other ways with C# as well. For example, you can use C# to write web services-a technique for sharing applications over the Internet. Of course, all of the other .NET languages provide XML and SOAP support, so this isn't a C# only feature. (Interestingly enough, you can't use Visual C++ for scripting in places such as web pages.)
Online Resources for SOAP and XML
SOAP and XML are new technologies that are in a state of flux. Consequently, you'll want to know where you can locate the latest information online. There are many useful online resources for SOAP and XML. The following list tells you about some of the more useful sites.
http://www.soap-wrc.com/webservices/default.asp is a site where you'll find great SOAP information.
http://msdn.microsoft.com/nhp/default.asp?contentid=28000523 also has information about the SOAP specification.
http://xml.org/ is one of the better places to find XML information.
http://msdn.microsoft.com/xml/default.asp also has good XML information.
http://www.xml.com/axml/axml.html has an annotated version, which can be good when you find the XML specification a little hard to understand.
http://www.webservices.org is of the better places to look for web services information in general. This site includes SOAP, XML, and .NET resources, as well as information about products and services from other companies.
Existing application interpretability Your company has a lot invested in existing applications. Any new programming language will have to produce applications that can interact with those existing applications. While you can't use C# to write code for existing applications, you can extend those applications through components. A component written in C# will look just like any other component to older applications.
Note You do need to register the component using RegAsm to make the component accessible. In addition, you need to either place the component in the application directory or use GacUtil to place a reference to the component in the Global Assembly Cache (GAC). A component requires less work than controls. If you want to create a managed control for use in an unmanaged application, you'll also need to add special interfaces, make registry entries, and perform additional testing to ensure that the control works as intended on the various Form Designer displays.
Short learning curve Visual C++ programmers will see many familiar constructs in C#. Except for learning a few new rules and ways of performing tasks, C++ developers will be able to start using C# immediately. Visual Basic developers will see some familiar elements, but the learning curve will be a little higher. Fortunately, gaining access to low-level programming functionality is well worth the price.
Reliability At one time, IT professionals looked at PCs as toys. Enlightened IT professionals might have looked at PCs as something useful for workgroup applications, but certainly not for anything mission critical. Today, developers do use the PC for mission-critical applications. The application has to work all the time and act in a predictable manner. The problem is that older languages don't tend to promote reliable application execution. In many cases, these languages leave fault detection as an exercise for the developer. C# changes all of this by taking a proactive approach to error detection and resolution.
Improved performance This is one area where the way you use C# will affect the benefit you receive. Microsoft's goal is to make distributed applications run faster, not all applications as a whole. Features like mapping XML data directly to C# structs, rather than relying on classes, will make web-based applications run faster. In addition, you'll gain performance benefits from C# scripts compiled as part of ASP.NET pages. The use of features like Code Behind makes creating ASP.NET pages easier than ASP, and you can use mixed languages within the scripts (if desired).
Application and component versioning Anyone who's gone through DLL hell will understand the importance of this feature. DLL hell occurs when you have two applicationsboth require the same DLL, but different versions of that DLL. The need to specifically override methods within a C# application reduces the problem of DLL hell by making the developer aware of the potential risks. Versioning support isn't automatic, but the goal, in this case, is to make the developer savvy about application interactions and what can happen when a method is overwritten.
Note You'll find the .NET Framework in the \WINNT\Microsoft.NET\Framework folder of your machine. This folder contains one folder for each version of the .NET Framework installed on your machine. An application uses the version of the .NET Framework that was in use when the developer created the application. While keeping multiple copies of the .NET Framework on the user's machine does increase the hard drive requirements for .NET; it also eliminates the problem of DLL hell. The application packaging process includes adding a copy of the version of the .NET Framework used to create the application. The resulting package is larger than a native EXE package (by as much as 45MB), but definitely complete. The .NET Framework is only installed if the client machine lacks the proper version of the .NET Framework for the application.
Metadata Support The goal, here, is to document and augment component behaviors so they reflect real-world processes. In many cases, there isn't any connection between a real-world behavior and the component implementing the behavior using older programming languages. By using metadata as a documentation technique, C# developers can create components that better reflect the business processes they're supposed to support.
An Overview C# and the .NET Platform
C# and the .NET Platform are closely coupled. In fact, every application you create will begin with a connection to the .NET Framework-the developer access portion of the .NET Platform. Yes, you can write unmanaged code under certain circumstances, but most people are going to want to use C# for its intended purpose of writing distributed applications. The easiest way to write managed code with C# is to use the .NET Framework.
Note C# does support work with unmanaged code. In fact, C# uses the unsafe keyword to enable developers to create unmanaged code within their applications. Normally, you'll restrict use of unsafe code to methods that use pointers. However, the unsafe keyword is a powerful feature that you could use for a broad range of purposes. So, how do you gain access to the .NET Framework from within C#? Create any program and you'll see that this line of code appears in every case: using System.
This line of code provides ready access to a specific level of .NET Framework services added through a reference in your code. If you want to access other portions of the .NET Framework, you'll add other using statements to the beginning of the application. In some cases, you might also need to use the Project → Add Reference command to display the Add Reference dialog box shown in Figure 1.1. This dialog box provides access to the various DLLs used to add functionality to your application.
Figure 1.1: The Add Reference dialog box provides access to .NET, COM, and Project components.
The .NET Framework uses a hierarchical list of services. Figure 1.2 shows a partial listing of these services as found in the .NET Framework SDK documentation. C# uses the same method (a menu entry) that Visual Basic does for adding references to these services. Adding the using System statement to your code means you don't have to write as much code-the compiler knows to look at the referenced service for methods it can't resolve normally.
Figure 1.2: The .NET Framework relies on a hierarchical list of services.
One of the main differences between project types in C# is the number and type of .NET Framework references automatically added to the project for you. The single reference shown in the examples in this briefing is the minimum for a console application. C# uses a more extensive list of .NET Framework services for even a small Windows application, as shown here:
using System;
using System.Drawing; using System.Collections;
using System.ComponentModel; using System.WinForms;
using System.Data;
Component developers will really like one of the features that the .NET Framework provideseasy access to the event log. Anyone who's worked with the event log in Visual Basic knows that while making an entry is easy, controlling the contents of the entry is frustrating at best because you don't have full access to the event log entries. Many Visual C++ developers don't even realize that you can make event log entries using API calls, and those who do wish for an easier way. Yes, you get full control over the event log entry in Visual C++, but the coding effort is a painful experience. When using C#, all you need is a reference to the System.Diagnostics namespace. The EventLog class provides complete access to the event log and with very little effort on the part of the developer.
As you can see, there's a tight connection between C# and the .NET Framework. You'll find that using the .NET Framework for your applications makes coding almost simple. As a result, the development cycle for C# projects is going to be much shorter than Visual C++ projects, once your development staff becomes familiar with the product.
Assemblies
An assembly is a complete compiled application entity. It contains the code and data for your application. The assembly also contains a manifest that lists the contents of the assembly and some of the assembly features. For example, the manifest contains the name of the company that developed the assembly. To gain a better understanding of an assembly, imagine creating the simple application containing two buttons. The application would display a simple message if you clicked one button and would close if you clicked the second. (You'll find this simple application in the \Chapter 01\Simple2 folder of the source code CD.)
Figure 1.3 shows the disassembly of the simple application. You can obtain this same view using the ILDASM (Intermediate Language Disassembler) utility to open the Simple2 application. As the figure shows, the assembly consists of the manifest and a Sample namespace. Under the Sample is the SimpleDialog class, which contains the buttons and other elements of the application.
Figure 1.3: An assembly contains several elements, including a manifest.
We'll dissect other applications as the book progresses because you can find out interesting information by disassembly and studying the IL created for your application. (See the "Working with a Common Language Base" section of Chapter 2 for details.) The point is that
assemblies are an ordered method of packaging an application or an application unit such as a component.
Attributes
Attributes are special features that enable you to describe an application that would normally require code. For example, you can use an attribute to define an event receiver or an event source. A single word or short set of words serves to augment some code within an application or a component.
So, why is this feature so important? Imagine writing the components you always have in the past, but with as little as 25% of the code you use today. Less code means fewer potential errors and a shorter development time. Programmers from all walks are finding they have a hard time meeting delivery dates, and are given shorter deadlines and increasing application complexity. Any technology that promises to reduce development time using a tool that you're already familiar with is a welcome relief.
We'll use attributes a lot throughout the book. Attributes are such a useful feature that using them is an essential part of learning C#. Once you learn how to use the built-in attributes, we'll also discuss creating custom attributes. Using custom attributes can significantly improve an already great feature. (See the section titled "An Attribute Example" in Chapter 3 for details.)
Other Language Interoperatiblity
All of the .NET languages are designed to work together with relative ease. In fact, you can use a mixed language environment when scripting. A component you create in C# will work with Visual Basic because both use the same IL. Mixing and matching languages that rely on the .NET Framework doesn't require much work. If you want to use a Visual Basic component in your C# application, simply place the component in the project folder or register the component in the GAC.
Working with non-.NET languages is a little harder, but not impossible. You can use your managed component in an unmanaged application, or your unmanaged component in a managed application. Microsoft provides a special namespace: System.Runtime.InteropServices and some special attributes to make interoperability easier. We'll discuss this topic further as the book progresses.
Understanding the Benefits of Using C#
In the previous sections of the chapter, you learned what C# is and what it has that you didn't have before. This is important, but some developers will still say, "So what?" Yes, C# does solve many problems that developers have with older languages, but experienced developers already know how to get around those issues and may see C# as yet another language to learn.
The fact is that C# has a lot to offer developers from a personal perspective. I wouldn't say any of these features are earth shattering, and you've probably heard these promises for other languages in the past. C# actually delivers on these promises and makes life easier for the developer. Will C# make you a better programmer? Yes, in some ways. For example, it helps
you catch more errors before they become problems. However, only experience creates great programmers.
Most developers will find that C# makes them faster and more efficient programmers. You'll spend less time figuring out how to code something due to an ambiguity in the development environment. In many cases, you'll also find that you spend less time searching for just the right API call or switch that isn't documented.
Now that you have some idea of what you have to gain from C#, let's discuss the topic in detail. The following sections answer the question, "What will C# do for me?" You'll learn why C# is such an important improvement in the development community.
Developer Productivity Enhancements
There's one overriding reason to use C#-it's the language of choice for many developers who work extensively with COM or other object-based development technologies. Spending even a small amount of time on the microsoft.public.dotnet.csharp.general, microsoft.public.dotnet.vb.general, and microsoft.public.dotnet.vc.general newsgroups shows widespread developer interest in C# as a language. (You can find all of these newsgroups on the news://news.microsoft.com server, if you can't find them on your local ISP.) Many developers on these newsgroups already plan to move to C# because it alleviates so many application development problems. In addition, Microsoft has submitted C# to the European standards group, ECMA (http://www.ecma.ch/), which means that the language will benefit from the efforts of a standards committee. (The http://www2.hursley.ibm.com/tc39/ website contains a better description of the standards effort.) Finally, more than one company is interested in C#, which could mean some level of platform independence for the language. The high interest in this language, coupled with a standards-oriented approach, means that developers will want to adopt C# relatively quickly.
Now that we've covered the main reason to move to C#, let's talk about all of the reasons to use it. The following sections will tell you about the benefits of C#, the prototyping and development speed, and how you can use C# to create better COM+ applications.
Simplicity
C# adds simplicity to the development environment in several ways. We've already talked about how Microsoft has simplified the data types by consolidating some and adding others. For example, you no longer need to worry about which char data type to use-there's only one. Likewise, the new decimal data type will greatly reduce programming complexity.
The use of the .NET Framework will simplify matters as well. The hierarchical structure of namespaces will make it easier to find methods that you need. In addition, more system resources are available as methods, rather than API calls. For example, with C# you can now write event log entries using a simple method call, rather than using the convoluted method for Visual C++.
One item I haven't mentioned yet is the IDE provided with Visual Studio .NET. Microsoft has added a variety of automation features to the product. For example, when you type a statement name, the IDE will automatically add the required braces for you. This feature
won't necessarily save a lot of time, but it should reduce the number of simple coding errors that programmer will have to find before an application compiles.
Managed environments simplify programming tasks. For example, C# will greatly reduce memory leaks using garbage collection. Of course, the use of garbage collection will also reduce debugging time because the programmer will have fewer errors to find. Since memory leaks are notoriously difficult to find and fix, most developers will find that garbage collection greatly reduces the amount of debugging time for a given project.
Consistency
There are many new types of consistency within C#. However, three forms deserve special mention because they have such a great impact on the development environment.
Everything is an object. C# even treats variables as objects. The runtime environment "boxes" variables into an object when you need to perform a task like data conversion. Once the data conversion is finished, the variable is unboxed. The point is that you can access everything in the same way-there aren't any special rules to remember.
The .NET Framework ensures function call consistency. Instead of having to remember a lot of very odd API calls, you just follow a hierarchy of namespace entries to the method you need to perform a specific task. Since every call is handled in the same way, the developer only needs to worry about the task at hand, rather than try to remember the odd exception to the rule that an API call might require.
Error trapping is easier than ever before. Unlike Visual C++ and Visual Basic where there are a number of ways to detect errors, C# uses a single standard method. This means that developers can standardize error-trapping routines and reduce the complexity of finding and eradicating problems like data entry errors.
Modern Development Options
Visual C++ and other languages were developed at a time when the Desktop was king. Vendors updated these languages with moderate success for the world of client/server programming. In the past few years, Internet development has become the area where most developers spend their time. Updates to these older languages now feel like kludges added to compensate for a development environment that vendors never designed these languages to address.
Given the need for distributed applications today, it's time for a new language that's designed to better meet the needs of modern developers. C# is that language. The use of a modern IDE and programming techniques will allow developers to gain the level of operating system access they require. We've talked about all of these features throughout this briefing, so I won't cover them again here.
Object Orientation
Unlike Visual C++ and Visual Basic, C# provides true object orientation. Everything is an object. This language does make some concessions for the sake of performance, but even in these areas, C# provides the means to use objects. For example, C# stores and uses variables
in the same way that Visual C++ and Visual Basic have in the past. The difference is that C# can box a variable within an object, making it easy to access the variable as an object when needed. This means that C# provides the same level of object orientation that languages like Eiffel and Smalltalk do, but without the performance penalties.
C# also embraces the COM+ virtual object system. This means that all objects execute within a context. You can assign role-based security to objects, which means that you can allow user interaction based on the role the user has within an organization. In short, you have much finer control over the component execution environment.
Finally, C# gets rid of the global variables, methods, and constants. Everything appears within a class. This means there are fewer chances for naming conflicts and the data contained within variables remains safer. While it will take some developers time to get used to the new method of handling data, the result is more reliable components and applications.
Compatibility
C# provides an environment that's compatible with everything that has gone before. If you really want to use the old APIs that you used in C programs long ago, C# provides a means to access them. Likewise, you have access to standard COM and OLE Automation through the APIs you've used in the past. C# provides access to all of the required data types through the COM+ runtime.
Flexibility
You'll find that C# is extremely flexible. It can't quite do everything that Visual C++ can. For example, if you need a native code output such as a DLL or EXE, then Visual C++ is the only choice when using Visual Studio .NET. However, in all other ways, C# is more flexible than anything that has gone before. You obtain all of the best features of Visual Basic and Visual C++ in one package.
Faster Prototyping and Development
To provide an honest evaluation in this section, you have to separate the benefits of using the new Visual Studio .NET IDE from the benefits of using C#. For example, everyone has access to the autocomplete and help features that the Visual Studio .NET IDE provides. While the new IDE does help you work faster, you'd also receive this benefit when using other languages.
C# provides its own set of productivity features. The way Microsoft put the language together means you'll spend less time guessing and more time writing code. You don't have to worry about pointers any longer. That alone should save both development and debugging time.
You'll also find that the organizational benefits of C# help you prototype and develop applications faster. The consistent look of every class you create means you spend less time worrying about structure and more time coding your project. However, as with any other new product, you'll spend some time overcoming the C# learning curve before you actually see the benefits of the new way of creating classes.
When C# Isn't the Right Choice
Developers are always looking for the silver bullet-the solution that works every time. Unfortunately, there aren't any silver bullets in the computer industry. While you can bend a computer language to your will and force it to perform a task, some tasks naturally work better with some languages. C# has limitations-some architectural and some as a matter of convenience. The following sections tell you about the areas where C# isn't necessarily the best language choice.
Native Executable Development
C# is the language of choice for many types of managed application development, those types of applications that rely upon the .NET Framework. However, C# can't provide native executables, those that rely exclusively on the underlying operating system. In fact, the only way to generate native executables with Visual Studio .NET is by using Visual C++. The lack of native code development potential means you can't use C# in situations where native executables are the only answer. The following list provides some ideas on when you should avoid using C# because of native code development requirements:
•Older versions of Windows
•Drivers and other low-level programming
•Downloadable components
It's especially important to consider your knowledge of the client for application services. Many existing Windows platforms lack .NET Framework support, which means they can't run managed applications. Consider the fact that the client would need to download such support before using your component if you used managed code when a native EXE would work better.
Older Application Support
Most companies have a wealth of existing code that they can ill afford to move to another development environment. These older applications might work fine as they are today or require small tweaks in order to keep pace with current technology. Even if you decide to build part of the application in a mixed environment (part managed and part unmanaged code), it's often better to continue using the current language. Continuing with Visual C++ or Visual Basic makes sense from a developer learning curve and code maintenance perspective when an application already relies on these products and has nothing to gain from using C#.
However, you should differentiate a local monolithic application from a distributed application on the Internet. Developing new services for an existing application using C# could make sense if the service is used for generalized access. For example, a web service that provides support to a company database for your company and several partners might make a good candidate for C#.
Older Platform Support
Microsoft has been touting platform independence as the reason to use .NET, yet the .NET Framework doesn't even run on all Windows platforms yet. As of this writing, there aren't any plans to port the .NET Framework to older Windows platforms, and the deafening quiet from
