This chapter introduces you to the syntax of the C# language. It’s assumed that you have a reasonable amount of experience with C++ or Java, because C# shares a similar syntax. In the first topic we will discuss the structure of a C# program, which is very similar to a JAVA program. 2.1 Structure of a C# program: Like any other Object-oriented language, classes are main building blocks of a C# program. A C# program may contain many classes of which only one class defines a main method. Classes contain data members and methods that operate on the data members of the class. Methods may contain data type declaration and executable statements. To write a C# program, we first define classes and then put them together. A C# program may contain one or more sections as shown in following figure: (Fig 2.1: General Structure of a C# program) Before we explain each section individually, let’s take two of the C# program’s example: Page 1 www.magix.in C# program structure (Console):- (Prog 2.1) C# program structure (Window):- (Prog 2.2) Now we will explain each section one by one:Page 2 www.magix.in Ø Documentation Section: The documentation section comprises a set of comment lines giving the name of the program, the author and other details, which the programmer would like to refer to at a later stage. Comments must explain ‘why’ and ‘what’ of classes and ‘how’ of algorithms. This would greatly help in maintaining the program. Ø Using Statements (import library files section): The next thing after documentation section (but before any namespace and class definitions) may be a number of ‘using’ statements. This is similar to the #include statement in C and import statement in JAVA. Example: using System.Windows.Forms; This statement instruct the interpreter to load the ‘Forms’ class contained in the namespace ‘Windows’, which is also under another namespace ‘System’. By ‘using’ statements, we can have access to classes that are part of other named namespaces. Ø Namespace and Type definition section: Classes can be grouped into bundles, referred to as Namespaces. Each file can contain one or more namespaces. A namespace can contain types such as classes, structs, interfaces, enumerations, and delegates, in addition to other namespaces. The following is the skeleton of a C# program that contains all of these elements: // A skeleton of a C# program using System; namespace MyNamespace1 { class MyClass1 { } struct MyStruct { } interface IMyInterface { } delegate int MyDelegate( ); Page 3 www.magix.in enum MyEnum { } namespace MyNamespace2 { } class MyClass2 { public static void Main(string[ ] args) { } } } Page 4 www.magix.in In parallel to understanding C# program structure, there are few points to remember: Ø C# is case sensitive. Ø All programming code should be written within a class. Every class should have a name. In the above example, there are two classes MyClass1 and MyClass2. Ø All programs should have a Main( ) method. Program execution always starts with the Main( ) method. Ø The Main( ) method should be declared as ‘static’, meaning that it would not be necessary to instantiate an object of the ‘MyClass2’ Class. Ø Every method should always indicate a return type. If the method does not return a value as in this case, it should be indicated with the keyword ‘void’. Ø Note that there is a semicolon behind the ‘using’ directive. Ø You can develop a C# program in any text editor. You can even do it in MS Word as long as you save the file as plain text with a .cs extension. Ø But a text editor, such as Notepad, does not provide IntelliSense or other environmental tools to make your life as a programmer easier. Ø The C# compiler comes free of charge as part of the .NET framework. In other words, we don't need Visual Studio to write and compile a C# program. Ø Note that semicolons are only added behind the actual program statements in the Main() method. No other program lines have semicolons. Ø Structure of a C# program include: o A program can consists of one namespace or hierarchy of namespace. o Namespace (if used otherwise directly program) consists of one or more classes and types. o A class consists of one or more methods. o A method consists of one or more statements. o Statements are group of C# tokens (i.e. keywords, variable, whitespaces etc. ) 2.2 Your First C# program: You’re probably eager to try your first program in C#. Let’s build our first program. You might not understand everything at this point, but you should get a feel for the process of writing, compiling, and running a real C# program. This demonstration uses a program named HelloWorld.cs, which does nothing more than display the words “HelloWorld” on the screen. This program is the traditional program used to introduce people to programming. Page 5 www.magix.in (Prog 2.1: HelloWorld.CS) Follow the steps in the next section to enter, compile, and execute HelloWorld.cs. Entering and Compiling HelloWorld.cs To enter and compile the HelloWorld.cs program, follow these steps: 1. Start your editor i.e. Notepad or VS. 2. Use the keyboard to type the HelloWorld.cs source code shown in Prog 2.1. Make sure that you enter the code using the same case. C# is case sensitive, so if you change the capitalization, you will get errors. 3. Save the source code. You should name the file HelloWorld.cs . But here comes another difference from java. Now you can name filename to whatever you want. You need not to stick as same filename as the public class name. 4. Compile HelloWorld.cs. If you are using the command-line compiler, enter the following: csc HelloWorld.cs Page 6 www.magix.in If you are using an Integrated Development Environment, select the appropriate icon or menu option. You should get a message stating that there were no errors or warnings. 5. Check the compiler messages. If you receive no errors or warnings, everything should be okay. If you made an error typing the program, the compiler will catch it and display an error message. For example, if you misspelled the word Console as Consol, you would see a message similar to the following: HelloWorld.cs(5,7): error CS0117: ‘System’ does not contain a definition for ‘Consol’. 6. Go back to step 2 if this or any other error message is displayed. Open the HelloWorld.cs file in your editor. Compare your file’s contents carefully with Listing Prog 2.1, make any necessary corrections, and continue with step 3. 7. Your first C# program should now be compiled and ready to run. If you display a directory listing of all files named HelloWorld (with any extension), you should see the following: HelloWorld.cs, the source code file you created with your editor HelloWorld.exe, the executable program created when you compiled HelloWorld.cs 8. To execute, or run, HelloWorld.exe, enter HelloWorld at the command line. The message HelloWorld is displayed onscreen. (Fig 2.2) Page 7 www.magix.in 2.2 Writing C# Code in the ASP.NET Framework: You'll find writing the C# code in VS.NET an easy task. You won't need to remember the complete set of functions and classes because of the pop-up IntelliSense menu, from which you can choose the required classes, methods, or functions. The key words are depicted in blue so that you can read and understand the codes with ease. Moreover, you won't have to struggle with missing or extra braces that can cause big headaches. In the VS.NET Framework, you need to write the C# code in a C# project. The following are the steps to create a C# project in the VS.NET Framework: 1. Select File → New → Project, to open the New Project dialog box. You can also press Ctrl + Shift + N to open the New Project dialog box. (Fig 2.3) 2. 3. 4. Select Visual C# Projects from the Project Types list. From the Templates pane, select (Windows->Empty Project). In the Name Box, specify the name of the project, say HW. In the Location box, specify the location, say “D:\Document and settings\Suraj Arora\My Documents\ Visual Studio 2005\Projects\”, where you want to create your project. The completed dialog box is shown in Figure 2.4 (Fig 2.4) Page 8 www.magix.in Note The Name and Location boxes contain a default project name and the location, respectively. You can either accept the default values or edit these boxes to specify the name of the project and the location. 5. Click OK. A new project is created and indicated in the Solution Explorer window (See Fig 2.5) (Fig 2.5: Solution Explorer for an empty project) 6. Because the project you created is empty, you need to add a class to it. To do so, select (Project -> Add Class). The Add New Item dialog box appears. 7. From the Templates pane, select C# Class. 8. In the Name box, type "HelloWorld." Click Open to create the class HelloWorld.cs. Notice that some preliminary code already is written in the class. Page 9 www.magix.in 9. In the given HelloWorld Class Main function, enter the following code: public static void Main( ) { Console.WriteLine("Hello World!!") ; } 10. Now the whole code should look like this: (Fig 2.6: The HelloWorld Class) 11. Select (Build -> Build HW) (or press Shift + F6). If no errors were detected in the code, the result of the code would also be displayed. If errors are reported, you'll need to check the project for syntax errors. 12. If there were no build errors, run the application by pressing F5. The output of the application is displayed at the console. But the console should disappear asap the result is shown. In normal case, even you wouldn’t be able to see the result. To get rid of this problem, insert the following line as the last line in the Main( ) function. It causes the program to pause until ENTER is pressed. If you omit this line, the command-line window will immediately disappear and you would not be able to see the output of your program: Console.ReadLine( ) ; 13. Now again either press F5 or click on the Start icon on the toolbar then the Console window opens and the following message is displayed: Hello World! Press any key to continue… Page 10 www.magix.in
© Copyright 2024