7
Chapter Five 5 The Structure of a C# Program After this chapter you should understand the role of Visual Studio in programming be able to develop a simple program outside Visual Studio and compile it understand the basic structure of a C# program understand the role of namespaces in a C# program understand how a C# program is saved Key concepts Visual Studio  Main() method Namespaces

Be sharp with C# (Chapter 5, Structure of a C# Program)

Embed Size (px)

Citation preview

8/14/2019 Be sharp with C# (Chapter 5, Structure of a C# Program)

http://slidepdf.com/reader/full/be-sharp-with-c-chapter-5-structure-of-a-c-program 1/7

Chapter Five

5The Structure of a C# Program

After this chapter you should

understand the role of Visual Studio in programming

be able to develop a simple program outside Visual Studio andcompile it

understand the basic structure of a C# program

understand the role of namespaces in a C# program

understand how a C# program is saved

Key concepts

Visual Studio

Main() method

Namespaces

8/14/2019 Be sharp with C# (Chapter 5, Structure of a C# Program)

http://slidepdf.com/reader/full/be-sharp-with-c-chapter-5-structure-of-a-c-program 2/7

Chapter 5 2 Structure of a C# Program

The role of Visual Studio

We must remember that C# is not equal to Visual Studio. The programming language is C#while Visual Studio is just the environment in which the program is developed to make it easier

for us. In fact, it is possible to write a C# program outside of Visual Studio and then compileand run it.

Things to do

Open Notepad or any other plain text editor and type the following lines of code. Save thefile with a .cs extension, e.g. Hello.cs .

class Hello{

static void Main(){

System.Console.WriteLine("Hello World!");System.Console.Write("Press any key to exit ...");System.Console.ReadKey();

}}

Open a command window:

Click on Start / Run …Type cmd in the text box and press OK.

Change the directory so that the folder

where your program file is saved is theactive folder. In the screen print below,the file Hello.cs is saved in theC:\BeSharp\Hello World directory.

(Hint: cd is a command for "Change directory". cd\ means that the directory (folder) mustbe changed to the root directory of the current disk. cd BeSharp\Hello World means that thedirectory must be changed to C:\BeSharp\Hello World .)

Type the full path and file name of the C# compiler in the .NET framework ( csc.exe )followed by a space and then the name of the file that you want to compile. See the

screen print below for an example.

If you press Enter now, you should see a message about the compiler version that wasused.

8/14/2019 Be sharp with C# (Chapter 5, Structure of a C# Program)

http://slidepdf.com/reader/full/be-sharp-with-c-chapter-5-structure-of-a-c-program 3/7

8/14/2019 Be sharp with C# (Chapter 5, Structure of a C# Program)

http://slidepdf.com/reader/full/be-sharp-with-c-chapter-5-structure-of-a-c-program 4/7

Chapter 5 4 Structure of a C# Program

All programming code should be written within a class. Every class should have a name.In the above example, the name of the class is Hello .

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 Hello class.Every method should always indicate a return type . If the method does not return avalue as in this case, it should be indicated with the keyword void .

Namespaces

Classes can be grouped into bundles, referred to as namespaces. In a line such as

System. Console .WriteLine( "Hello World!" );

the word System refers to a namespace that contains the Console class. We can add ausing directive (this is not a statement) before a class to indicate to the compiler that itshould search for a class in a specific namespace. In other words, we can change theprogram above to limit the amount of typing and, to some extent, also enhance readability:

using System;class Hello{

static void Main()

{ Console .WriteLine( "Hello World!" );Console .Write( "Press any key to exit ..." );Console .ReadKey();

}}

Note that there is a semicolon behind the using directive.

We can also define our classes inside a namespace, for example:

using System;namespace Hello{

class Hello{

static void Main(){

System. Console .WriteLine( "Hello World!" );System. Console .Write( "Press any key to exit ..." );System. Console .ReadKey();

}}

}

Open the last console application that you developed in Visual Studio again and inspect the

code that was generated by Visual Studio. You should be able to understand the structureof the program better now.

Namespace Class Method Parameter

8/14/2019 Be sharp with C# (Chapter 5, Structure of a C# Program)

http://slidepdf.com/reader/full/be-sharp-with-c-chapter-5-structure-of-a-c-program 5/7

Chapter 5 5 Structure of a C# Program

using System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace Hello_World{

class Program {

static void Main( string [] args){}

}}

Note that, besides the System namespace, Visual Studio also added some othernamespaces in using directives. Visual Studio has no way to tell in advance which classesyou will be using in your program and included the most common namespaces by default.Depending on the classes that you need, you may delete some of these using directives

without any effect on the program.

For the time being, you can ignore the arguments between the brackets of the Main()

method. We will discuss that at a later stage.

The file structure of a C# program

Open Windows Explorer and browse to the folder where you saved the program that youdeveloped in a text editor.

You should see only two files, namely the original text file with a .cs extension (cs = "CSharp") and the .exe (executable) file. The .exe was generated by the csc compiler and itis this file that can be distributed to users.

Again, in Windows Explorer , browse to the last console application that you developed inVisual Studio. You will notice many more files that Visual Studio generated as part of theproject.

Solution folder

Project folder

Project file

8/14/2019 Be sharp with C# (Chapter 5, Structure of a C# Program)

http://slidepdf.com/reader/full/be-sharp-with-c-chapter-5-structure-of-a-c-program 6/7

Chapter 5 6 Structure of a C# Program

- Visual Studio allows the grouping of one or more projects into a solution. All files of asolution is saved in a solution folder. The .sln (solution) file organizes all project itemsand keeps track of file names and their locations on disk. This is the file that must beopened when you want to return to an existing solution.

- The .csproj (C Sharp project) file keeps track of forms and classes in your project and

their locations on disk. Since we are mostly working with solutions that contain a singleproject, you can open the .csproj file with the same effect as opening the .sln file. Thisfile is normally located in the project folder, which is a sub-folder of the solution. It willoften happen that the solution and the project have the same name and therefore thesolution folder and the project folder will have the same name.

- The .cs (C Sharp) files contain the C# program code. These files are normally locatedin the project folder, which is a sub-directory of the solution directory.

- The /Bin/Debug sub-folder contains an .exe (executable) file which can be executedoutside of Visual Studio. Note that you cannot distribute this file to users who do nothave Visual Studio installed.

- If you want to distribute a .exe to users who do not have Visual Studio, you shouldselect Release in the Solution Configurations dropdown box (see screen print below).When you run the program, a /Bin/Release sub-folder will be created which contains a.exe file that can be distributed.

The file structure of Windows Forms applications that are created in Visual Studio looksvery similar to that of console applications. There are, however, some differences.

- One of the .cs files (called Program.cs unless you changed its name) contains the Main() method. This method contains a line of code that will instantiate and displaythe first (or only) form in the program. The contents of this file were generated byVisual Studio.

- Visual Studio will create a class for every form that is added to the project. A formclass is split over two files and every file will thus contain a partial class .

One of the files (extension .cs ) contains the C# code that you entered for the eventhandlers.

The other file (extension .designer.cs ) contains C# code to define the form and thegraphical components on the form. This code is generated automatically by VisualStudio as you drag and drop controls from the toolbar and set their properties. It isnormally not good practice to tamper with the contents of this file.

- Later, when you develop your own classes, they will also be saved in files with a .cs

extension.

- Note that all classes that belong to the same project will be part of the samenamespace.

8/14/2019 Be sharp with C# (Chapter 5, Structure of a C# Program)

http://slidepdf.com/reader/full/be-sharp-with-c-chapter-5-structure-of-a-c-program 7/7

Chapter 5 7 Structure of a C# Program

Keywords

You should make sure that you know what each of these items mean or where they are used.

.cs

.csproj

.designer.cs

.exe

.slnC#Change directoryclassClassCompilerConsole

cscDirectoryExecutable fileFile structureFolder Main()MethodNamespaceParameter partial classPath

Projectreturn typeRelease versionSolutionstaticSystem namespaceusingVisual StudiovoidWindows Explorer

Key:

Concepts : NormalClasses and Controls : Green, e.g. ColorMethods : Bold with brackets, e.g. Main()Reserved words : Blue, e.g. class

Exercise1. Write a C# program in a text editor such as Notepad to allow the user to enter the

names and test marks for 5 students. The program should then display a completeclass list with the class average to one decimal digit. Output should be properly alignedas in the example below.

(You may think about doing it in Visual Studio first to sort out all the errors and thencopy and paste it into Notepad . Don't do it, this way you would not get the feeling of doing it in a "dumb" environment.)