The Hello World Example


Writing a Hello World application is far from original, but a direct comparison of Hello World in C++ and C# can be quite instructive for illustrating some of the differences between the two languages. In this comparison, we've tried to innovate a bit (and demonstrate more features) by displaying "Hello World!" both at the command line and in a message box. A slight change has also been made to the text of the message in the C++ version, in a move which we emphasize should be interpreted as a bit of fun rather than a serious statement.

The C++ version looks like this:

#include <iostream> #include <Windows.h> using namespace std; int main(int argc, char *argv) {    cout << "Goodbye, World!";    MessageBox(NULL, "Goodbye, World!", "", MB_OK);    return 0; }

Here's the C# version:

 using System; using System.Windows.Forms; namespace Console1 { class Class1 { static int Main(string[] args) { Console.WriteLine("Hello, World!"); MessageBox.Show("Hello, World!"); return 0; } } } 

Comparing the two programs tells you that the syntax of the two languages is quite similar. In particular, code blocks are marked off with braces ({}), and semicolons are used as statement delimiters. Like C++, C# ignores all excess whitespace between statements. You'll go through the samples line by line, examining the features they demonstrate.

#include Statements

The C++ version of Hello World starts with a couple of preprocessor directives to include some header files:

#include <iostream>  #include <Windows.h>

These are absent from the C# version, something that illustrates an important point about the way that C# accesses libraries. In C++ you need to include header files in order for the compiler to be able to recognize the relevant symbols in your code. You need to instruct the linker separately to reference the libraries, achieved by passing command-line parameters to the linker. C# doesn't really separate compiling and linking in the way that C++ does. In C#, the command-line parameters are all that is required(and only then if you are accessing anything beyond the basic core library). By themselves, these will allow the compiler to find all the class definitions; hence explicit references in the source code are unnecessary. This is actually a much simpler way of doing it — and indeed once you've familiarized yourself with the C# model, the C++ version, in which everything needs to be referred to twice, starts to look rather strange and cumbersome.

One other point you should note is that of the two #include statements in the preceding C++ code, the first accesses an ANSI standard library (the iostream part of the standard library). The second is a Windows-specific library and is referenced to display the message box. C++ code on Windows often needs to access the Windows API because the ANSI standard doesn't have any windowing facilities. By contrast, the .NET base classes — in a sense, the C# equivalent of the ANSI standard template library — do include windowing facilities, and only the .NET base classes are used here. The C# code requires no non-standard features. (Although arguably, this point is balanced by the fact that standard C# is only available on Windows, at present.)

Although the preceding C# code happens not to have any #include directives, it's worth noting that some preprocessor directives (though not #include) are available in C# and do retain the # syntax.

Namespaces

The C# Hello World program starts with a namespace declaration, which is scoped by the curly braces to include the entire program. Namespaces work in exactly the same way in C# as they do in C++, providing ways to remove possible ambiguity from the names of symbols in the program. Placing items in a namespace is optional in both languages, but in C# the convention is that all items should be in a names- pace. Hence, whereas it is very common to see C++ code that is not contained in a namespace, it is extremely rare to see such code in C#.

For the next part of the code, the C# and C++ versions are very similar — both use the statement using to indicate the namespace in which any symbols should be searched for. The only difference is a syntactical one: The statement in C# is just using, whereas in C++ it is using namespace.

Many C++ developers will be used to the old C++ library, which meant including the file iostream.h rather than iostream — in which case the using namespace std statement is unnecessary. The old C++ library is officially deprecated, and the previous example demonstrates how you really should be accessing the iostream library in C++ code.

Entry Point: Main() versus main()

The next items in the Hello World examples are the program entry points. In the C++ case this is a global function named main(). C# does roughly the same thing, although in C# the name is Main(). However, whereas in C++ main() is defined outside of any class, the C# version is defined as a static member of a class. This is because C# requires all functions and variables to be members of a class or struct. C# will not allow any top-level items in your program except classes and structs. To that extent C# can be regarded as enforcing stricter object-oriented practices than C++ does. Relying extensively on global and static variables and functions in C++ code tends to be regarded as poor program design anyway.

Of course, requiring that everything should be a member of a class does lead to the issue of where the program entry point should be. The answer is that the C# compiler will look for a static member method called Main().This can be a member of any class in the source code, but only one class should normally have such a method. (If more than one class defines this method, a compiler switch will need to be used to indicate to the compiler which of these classes is the program entry point.) Like its C++ counterpart, Main() can return either a void or an int, though int is the more usual. Also like its C++ equivalent, Main() takes the same arguments — either the set of any command-line parameters passed to the program, as an array of strings, or no parameters. But as you can see from the code, strings are defined in a slightly more intuitive manner in C# than they are in C++. (In fact, the word string is a keyword in C#, and it maps to a class defined in the .NET base class library, System.String.) Also, arrays are more sophisticated in C# than in C++. Each array stores the number of elements it contains as well as the elements themselves, so there is no need to pass in the number of strings in the array separately in the C# code, as C++ does via the argc parameter.

Displaying the Message

Finally, you get to the lines that actually write your message — first to the console, then to a message box. In both cases these lines of code rely on calling up features from the supporting libraries for the two languages. The classes in the standard library are obviously designed very differently from those in the.NET base class library, so the details of the method calls in these code samples are different. In the C# case, both calls are made as calls to static methods on base classes, whereas to display a message box C++ has to rely on a non-standard Windows API function, MessageBox(), which is not object-oriented.

The base classes are designed to be highly intuitive — arguably more so than the standard library. Without any knowledge of C#, it's immediately obvious what Console.WriteLine() does. If you didn't already know, you'd have a hard time figuring out what cout << means. But in the commercial world of programming, being easy to understand is usually worth more than being artistic.

MessageBox.Show() takes fewer parameters than its C++ equivalent in this example, because it is overloaded. Other overloads that take additional parameters are available.

Also, one point that could be easy to miss is that the code demonstrates that C# uses the period, or full stop, symbol (.) rather than two colons (::) for scope resolution. Console and MessageBox are the names of classes rather than class instances! In order to access static members of classes, C# always requires the syntax <ClassName>.<MemberName>, whereas C++ gives you a choice between<ClassName>::<MemberName> and <InstanceName>.<MemberName> (if an instance of the class exists and is in scope).




Professional C# 2005
Pro Visual C++ 2005 for C# Developers
ISBN: 1590596080
EAN: 2147483647
Year: 2005
Pages: 351
Authors: Dean C. Wills

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net