|
|
| Home | Forum |
| C#:: Not Just Another Programing Language | .NET Framework |
|
Former President Clinton was renowned for his ability to compartmentalize, to put different aspects of his life into imaginary boxes and keep them separate from one another. Compartmentalization also describes the current state of affairs in Windows programming. To a very large extent, the language that a Windows developer chooses determines the application programming interface (API) that he or she uses to make requests of the operating system or other applications. A Visual Basic developer, for example, uses an API specific to Visual Basic. A C programmer probably writes directly to the Win32 API. Most C++ developers use the Microsoft Foundation Classes (MFC), which have an API all their own that encompasses large portions of the Win32 API. Because each of these APIs is very different, it’s difficult for a Windows developer to switch languages. Switching from Visual Basic to C++ isn’t just a matter of learning a new programming language; it also means coming to grips with a new API. One of the most remarkable features of Microsoft’s much talked-about .Net platform is that it provides a common API for a number of widely used programming languages. For the first time in the history of the industry, the choice of programming language becomes little more than a matter of lifestyle, and an application written in Visual Basic isn’t significantly different than an application written in C++. The .Net API is provided by a huge set of classes (currently numbering more than 3,500) called the .NET Framework Class Library, or FCL for short. The same FCL class that allows you to open a file in Visual Basic also allows you to open it in C++. Furthermore, in the world of .Net, language compilers are nothing more than tools for producing Microsoft Intermediate Language (MSIL). MSIL is a pseudo-machine language that isn’t tied to a particular processor. When a .NET application executes, a runtime engine called the Common Language Runtime (CLR) compiles MSIL into native machine code on the fly—a process known as just-in-time (JIT) compiling—and executes it in a highly managed environment that features automatic garbage collection, type safety, and much more. With few exceptions, anything one developer can do in C++ another can do in Visual Basic, Perl, or whatever language he or she chooses. All of these languages are merely syntactic devices for producing MSIL that can be executed by the CLR. And all of them enjoy access to the richness of the FCL. Microsoft intends to provide five language compilers for .NET: Visual Basic, C++, C#, JScript, and MSIL. Third parties are actively working on .Net compilers for about 25 other languages, including Smalltalk, Perl, Python, Eiffel, and yes, even COBOL. But the language that has garnered the most attention by far is C# (“C-Sharp”). C# has become a lightning rod of sorts for the anti-Microsoft camp and is frequently characterized, fairly or not, as Microsoft's answer to Java. In reality, C# is a relatively minor player in the .Net initiative. It’s one of many languages that a developer can use to write .Net apps. It's arguably the best language as well, because it’s the only one built from the ground up for .Net. But at the end of the day, arguing the merits of C# versus Java is a red herring. It's the .NET Framework—the combination of the CLR and the FCL—that is the essence of .Net. C# is merely the cherry on top. These points nonwithstanding, C# could become one of the most popular programming languages ever if developers embrace .Net. Few C++ programmers that I know write .Net code in C++; most use C# instead. It's an easy transition, and C# code is more elegant and understandable than the equivalent code written in C++. Even a few Visual Basic developers I know are moving—or are considering moving—to C#. In all likelihood, the vast majority of .Net developers will do their work in either VB or C#. If .Net is in your future, then there’s a good chance that C# is, too. The C# Programming Language Since the days of Kernighan and Ritchie's The C Programming Language, the "Hello World" application has served as the canonical demonstration program for language newcomers. Here’s how Hello World looks in C#: class MyApp Here’s how the C# version of Hello World works. Every C# application has it in a class or other data type with a static method named Main. Main is the entry point—the method that executes when the application begins running. This implementation of Main uses the WriteLine method of the Console class found in the System namespace of the .NET Framework Class Library to produce its output. Console is one of many classes in the System namespace, and System is one of about 100 namespaces in the FCL. FCL classes are divided into hierarchical namespaces to lend organization to what would otherwise be a large and intimidating list of class names. The System namespace includes important classes such as Console and also defines the base data types—bytes, integers, and so on—used by all .Net applications, regardless of the language in which they’re written. Because using fully qualified class names—that is, class names prefaced by namespace names—can grow cumbersome, C# supports a "using" statement that permits developers to use classes in designated namespaces without typing namespace names. The following version of Hello World uses the "using" statement to make referencing classes defined in the System namespace syntactically easier: using System; Syntactically, C# is a lot like Java and C++. It supports familiar flow-control statements such as "if," "switch," "while," and "for," and throws in a handy "foreach" statement for iterating over collections. It supports the three principal tenets of object-oriented programming—encapsulation, inheritance, and polymorphism—using the same basic paradigms employed by C++ and Java. User-defined types are defined by declaring classes and structs, and a derived type inherits all the members of its base type. (Because user-defined types are compiled to MSIL and fully described in metadata, it's even possible to write a class in VB and base a derived type on it in C#, or vice versa.) Like Java, C# supports single inheritance only, although a C# class can derive from multiple interfaces, which are similar to Java interfaces-bundles of abstract methods that are implemented in a derived class and serve as a contract of sorts between a data type and users of that data type. Like C++, C# supports polymorphism by permitting methods to be declared virtual. A key difference between C# and the languages that it’s frequently compared to is what you can put in a class or struct. C++ has member variables and member functions; Java has member variables and methods, and supports a richer variety of type members: Fields, which are analogous to member variables class Rectangle Rectangle rect = new Rectangle (3, 4); rect.Resize (5, 6); Console.WriteLine ("Area = {0}", rect.Area); Because C# code compiles to MSIL that runs in the managed environment of the CLR, destruction in C# is nondeterministic. That means the Rectangle object has no destructor per se and isn't cleaned up at any precise point in time; rather, it#146;s cleaned up when the garbage collector sees fit. There is no delete statement in C#, because the garbage collector handles all memory deallocations. Another key feature of C# is the distinction between classes and structs. Classes define reference types, which means bundles of code and data allocated on the garbage-collected heap. Structs define value types, which are allocated on the stack. Stack allocations are faster but are not garbage-collected as heap allocations are. A data type called Point defined in the following way is a reference type: class Point One of C’s most innovative features is its support for attributes. An attribute is a declaration in your code that attaches additional information to an element of that code such as a class or a class member. The predefined Conditional attribute is used to enact conditional execution. In the following example, calls to Foo only execute if the code was compiled with the symbol “DEBUG” defined: [Conditional ("DEBUG")] When it comes to error handling, C# uses an exception handling mechanism based on "try ... catch" blocks that will be instantly familiar to Java and C++ programmers. The .NET Framework Class Library and the CLR itself always report errors by throwing exceptions, never by simply returning error codes, so learning to trap exceptions and handle them gracefully will be de rigueur for new C# programmers. C# in Action The real power of C# lies not in its syntax, but in the fact that C# applications enjoy unfettered access to the facilities of the .NET Framework Class Library. As an example, consider Web services. When Microsoft talks about .Net to its customers, it frequently talks about Web services-applications that run on Web servers and expose content and functionality to Web clients by listening for (and responding to) requests encapsulated in SOAP (Simple Object Access Protocol) packets. You don’t have to have .Net to write Web services or Web service clients, but the FCL makes writing both of them incredibly easy. And C# is a great way to leverage that functionality in the FCL. Suppose, for example, that your company wants to implement a service that Internet clients can call to perform mortgage calculations. You could write a few thousand lines of code that parses SOAP requests, performs the requisite calculations, and returns the results as XML. Or you could write just a few lines of C#: <%@ WebService Language="C#" Class="MCalc" %> Examples of incredible things that you can do with just a few lines of code in C# abound. For example, one line of C# can extract an image from a JPG file; another line can render that image on the screen. One more line can serialize a set of database records into an XML file. In every case, the power isn’t in the language but in the platform underlying it. And the same power is available to all .Net-supported languages. Furthermore, Web services are just one of several types of applications that you can write with C# and other .Net programming languages. Others include GUI applications (Windows Forms), Web applications (Web Forms), NT services, and, of course, Windows console applications. Summary It should be evident by now that C# is not a general-purpose programming language. It exists solely to help you write .Net code, and it’s just one of many languages that you can choose from for doing that. Nonetheless, because it’s the only language specifically designed for .Net, it’s likely to be one of the most popular, too, second only perhaps to Visual Basic. The fact that C# isn’t alone among .Net programming languages won’t diminish its importance in the least. Syntactic similarities between C# and Java will invite inevitable comparisons, but fundamentally these two languages are two different products designed to realize two very different goals. To be sure, C# isn’t perfect. Underlying differences between value types and reference types can lay a trap for the unwary programmer, and nondeterministic destruction causes a set of problems all its own that can be exacerbated in C#. But what about those who claim that language agnosticism prevents a tight coupling between language and runtime and will be detrimental to the platform as a whole? That’s wishful thinking on their part. C# is as tightly bound to the CLR as Java is to the JVM, and anyone who tells you differently probably works for Sun. C# won’t succeed or fail on its own merits. Its destiny is tied
to the success or failure of .Net. History, however, has shown that
betting against Microsoft is a sucker’s bet. There’s no
reason to think that things will be any different this time around |
|