C # Sharp experience: "Hello, world !" Program

Source: Internet
Author: User
Tags mscorlib

Li Jianzhong (Nanjing University of Posts and Telecommunications (Cornyfield@263.net)

C # is a simple, modern, elegant, object-oriented, type-safe, and platform-independent new component programming language. Its Syntax style is derived from the C/C ++ family. It integrates the efficiency of Visual Basic and the power of C/C ++. It is Microsoft's Microsoft, which laid the foundation for its next Internet dominance.. NET platform. It was well received and loved by programmers from all over the world with its powerful operation capabilities, elegant syntax style, innovative language features, and first-class support for component-oriented programming. "It is the computer language I have dreamed of over the years !" -- Many senior programmers are surprised to get C. From the name of C # Language (C sharp), we can also see Microsoft's ambitious ambition to use it to build its next-generation Internet deep service. C # The language has been submitted by Microsoft to ECMA of the European Computer Manufacturers Association. After standardization, C # can be developed and supported by any vendor on any platform, this provides a powerful driving force for C # development. Here we can also see the unprecedented vision and wisdom of Microsoft.

Component Programming has become a consistent choice for the next generation of program development in today's world's software industry. It is a deep development of object-oriented programming in 1990s. C # at the time of birth, taking full advantage of the day, "first-class support for component-oriented programming" is by no means easy to talk about. In fact, the component feature has been deeply embedded into all aspects of the C # language, which is a sharp aspect of C. In the following article, I will show the component features of C # language from all aspects, and elaborate on C # component-oriented programming in depth. The entire topic is divided into ten lectures:"First, 'Hello, world! 'Program","Lecture C # BASIC Language Introduction","Third, the basic structure of the Microsoft. NET platform","Class 4 and objects","5. constructor and destructor","Method 6","Lecture 7 domain and attributes","8. Reload the indexer and operator"," Array and string 9 "," feature and ing ", and" 11th about com interoperability unmanaged programming and Exception Handling ", "12th. Use C # to weave the future-C # programming model overview ".

Lecture 1 "Hello, world !" Program

"Hello world !" A program is a romantic convention that programmers have always made and a great dream. One day, computers from human hands will say "Hello World!" to this beautiful world !". It is a good starting point for learning a new language. Let's start from here and look at the following example:

//HelloWorld.cs by Cornfield,2001//csc HelloWorld.csusing System;class HelloWorld{public static void Main(){Console.WriteLine("Hello World !");}}

We can open the simple "Notepad" program that comes with windows to compile this code. I recommend a very clear editing tool that exposes the program code at the beginning. We save the file name as helloworld. CS, where ". cs" is the extension of the C # source code file. Then, type the " helloworld. cs" Compilation file in the command line environment of the C # compiler. You can see the output file helloworld.exe. We typed helloworld to execute this file to get the following output:

Hello world!

Next we will carefully analyze the above Code and the compilation and output of the entire program and the execution process. First look at the two lines of code starting from the file. This is a single line comment statement in C. Similar to the C ++ language, C # supports two annotation Methods: single-line annotation starting with "//" and "/*", "*/" indicates the multi-line annotation used for pairing. Annotations cannot be nested.

Next, let's take a look at the following "using system;" statement. This is the using namespace directive of c #. Here, "system" is a class library provided by Microsoft. NET. C # The language does not have its own language library. It directly obtains the Microsoft. NET system class library. The Microsoft. NET Class Library provides very powerful general functions for our programming. This statement allows us to use a short alias "console" to replace the type "system. Console ". Of course, the using indicator is not required. We can use the global name of the type to obtain the type. In fact, the using statement does not affect the C # compilation and output programs at all. It only simplifies the type reference method of a long namespace.

Then we declare and implement a helloworld class containing the static main () function. C # All declarations and implementations must be placed in the same file. Unlike C ++, the two can be separated. The main () function is very special in C #. It is the entry point for all executable programs specified by the compiler. Due to its particularity, we have the following guidelines for the main () function:

  1. The main () function must be encapsulated in a class or structure to provide the entry point of the executable program. C # adopts a completely object-oriented programming method. In C #, global functions such as C ++ cannot be used.
  2. The main () function must be a static function ). This allows C # To run programs without creating instance objects.
  3. There are no special requirements for the protection level of the main () function. Public, protected, private, and so on can all be used, but we usually specify it as public.
  4. The first letter of the main () function name must be in uppercase; otherwise, it does not have the semantics of the entry point. C # is a case-sensitive language.
  5. The main () function has only two parameters: the command line parameters without parameters and the string array, that is, static void main () or static void main (string [] ARGs ), the latter accepts command line parameters. A c # program can have only one main () function entry point. Parameters of other forms do not have entry point semantics. C # does not recommend that you use other parameters to overload the main () function, which causes compilation warnings.
  6. The Return Value of the main () function can only be void (no type) or int (integer type ). Other forms of return values do not have entry point semantics.

Let's take a look at the internal implementation of the main () function in the "helloworld. cs" program. As mentioned above, the console is a class under the namespace system, which represents the console we normally deal. Here we call its static method writeline (). Like C ++, static methods allow us to directly act on classes rather than instance objects. The writeline () function accepts the string type parameter "Hello world! ", And send it to the console for display. As mentioned above, C # does not have its own language library. It directly obtains the Microsoft. NET system class library. Here, we can get system. Console. writeline () in the Microsoft. NET system class library to complete the console output operations we want. This completes "Hello world! "Program.

But things are far from that simple! While compiling and outputting execution programs, many underlying mechanisms of Microsoft. NET are surging. to experience the sharpness of C #, we have no reason to ignore the Microsoft. NET platform backed by it. In fact, without the Microsoft. NET platform, it is hard to say what is sharp about C. Let's take a look at what happened after the "helloworld. cs" file is compiled with the csc.exe command. Yes, we have to go to the helloworld.exe file. But that's an example. The helloworld.exe is not an executable file! So what is it? Why can it be executed?

Okay. Here is the answer to these questions. First, the compiled output helloworld.exe is an intermediate language (IL), metadata (metadata) and an additional standard executable file header of the target PLATFORM added by the compiler (for example, the Win32 platform adds a standard Win32 executable file header) (portable executable, but not traditional binary executable files-although they have the same extension. An intermediate language is a set of CPU-independent instruction sets that can be translated by the instant compiler jitter into local code on the target platform. The intermediate language code makes the C #, VB. NET, and VC. NET languages of all Microsoft. NET platforms independent of each other and implement interoperability between languages. Metadata is a collection of tables embedded in PE files. Metadata describes the data types in the Code and other information that must be known during code execution in the common language runtime. Metadata enables the. NET application code to have a custom description feature and provides type security assurance. In the past, an additional type library or Interface Definition Language (IDL) was required ).

This explanation may be a bit confusing, so let's take a look at this PE file. The tool we use is. Net SDK beta2's ildasm.exe, which can help us extract relevant data from PE files. Run the "ildasm/output: helloworld. Il helloworld.exe" command to obtain two output files: helloworld. Il and helloworld. Res. The latter is the extracted resource file for the moment. Let's look at the helloworld. Il file. We can use the "Notepad" program to open the metadata and the intermediate language (IL) code. Due to the length relationship, we only extract the intermediate language code and list it below, we will not talk about the table items related to metadata for the moment:

class private auto ansi beforefieldinit HelloWorld       extends [mscorlib]System.Object{  .method public hidebysig static void  Main() cil managed  {    .entrypoint    // Code size       11 (0xb)    .maxstack  8    IL_0000:  ldstr      "Hello World !"    IL_0005:  call       void [mscorlib]System.Console::WriteLine(string)    IL_000a:  ret  } // end of method HelloWorld::Main  .method public hidebysig specialname rtspecialname           instance void  .ctor() cil managed  {    // Code size       7 (0x7)    .maxstack  8    IL_0000:  ldarg.0    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()    IL_0006:  ret  } // end of method HelloWorld::.ctor} // end of class HelloWorld

The rough idea is that it is similar to the earlier assembly language, but it has the object definition and operation functions. We can see that it defines and implements a helloworld class inherited from system. Object and two functions: Main () and. ctor (). Where. ctor () is the constructor of the helloworld class. It can be found in "helloworld. CS "We didn't define constructors in the source code -- yes, we didn't define constructors, but the C # compiler added them to us. You can also see that the C # compiler also forces the helloworld class to inherit the system. Object Class, although this is not specified. We will analyze these advanced topics in future lectures.

How is the PE file executed? The following is the execution process of a typical C #/. NET application:

  1. The application (PE file) that the user executes the compiler output, the operating system loads the PE file, and other DLL (. NET Dynamic Connection Library ).
  2. The operating system loader jumps to the program entry point based on the executable file header in the preceding PE file. Obviously, the operating system cannot execute an intermediate language. This entry point is also designed as the _ corexemain () function entry to jump to mscoree. dll (. NET platform core supports DLL.
  3. The corexemain () function starts to execute the intermediate language code in the PE file. The execution here refers to the compilation cost of the Local Binary Code by using the instant compiler based on the called object method in the general language runtime, which is executed and stored in the machine cache as needed.
  4. During program execution, the garbage collector is responsible for memory allocation, release, and other management functions.
  5. After the program is executed, the operating system uninstalls the application.

A clear understanding of the execution process of compiled and output PE files is the key to a deep understanding of C # programming. This process itself interprets the advanced Kernel Mechanism of C # language and Microsoft behind it. NET platform. A "Hello world! "The program has enough generalization power. After we have a good starting point for the C # language, the following topics will share with you the C # basic language and explore Microsoft. NET platform construction, step by step to experience the C # cutting-edge programming world, let's go!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.