C# Day 1- Basics (part 1)

57 views

This chapter gives you a good start in that direction by providing you with a basic knowledge of the
fundamentals of C# programming, which is built on in subsequent chapters. The main topics
covered are:
❑ Declaring variables
❑ Initialization and scope of variables
❑ Predefined C# data types
❑ Dictating the flow of execution within a C# program using loops and conditional
statements
❑ Enumerations
❑ Namespaces
❑ The Main() method
❑ Basic command - line C# compiler options
❑ Using System.Console to perform console I/O
❑ Using comments and documentation features
❑ Preprocessor directives
❑ Guidelines and conventions for good programming in C#
By the end of this chapter, you will know enough C# to write simple programs, though without
using inheritance or other object - oriented features, which are covered in later chapters.

Your First C# Program

Let ’ s start by compiling and running the simplest possible C# program — a simple class consisting of a
console application that writes a message to the screen.
Later chapters present a number of code samples. The most common technique for writing C# programs
is to use Visual Studio 2008 to generate a basic project and add your own code to it. However, because
the aim of these early chapters is to teach the C# language, we are going to keep things simple and avoid
relying on Visual Studio 2008 until Day 15 , “ Visual Studio 2008. ” Instead, we will present the code
as simple files that you can type in using any text editor and compile from the command line.

The Code

Type the following into a text editor (such as Notepad), and save it with a .cs extension (for example,
First.cs ). The Main() method is shown here:
using System;

namespace  Csharp.Basics
{
            class MyFirstCSharpClass
           {
               static void Main()
                 {
                    Console.WriteLine(“This isn’t at all like Java!”);
                     Console.ReadLine();
                     return;
                }
           }
  }

Compiling and Running the Program

You can compile this program by simply running the C# command - line compiler ( csc.exe ) against the
source file, like this:
csc First.cs
If you want to compile code from the command line using the csc command, you should be aware that
the .NET command - line tools, including csc , are available only if certain environment variables have
been set up. Depending on how you installed .NET (and Visual Studio 2008), this may or may not be the
case on your machine.

If you do not have the environment variables set up, you have the following two options. The first is to run
the batch file %Microsoft Visual Studio 2008%\Common7\Tools\vsvars32.bat from the
command prompt before running csc , where %Microsoft Visual Studio 2008 is the folder to
which Visual Studio 2008 has been installed. The second, and easier, way is to use the Visual Studio 2008
command prompt instead of the usual command prompt window. You will find the Visual Studio 2008 command
prompt in the Start Menu, under Programs, Microsoft Visual Studio 2008, Microsoft Visual Studio Tools.
It is simply a command prompt window that automatically runs vsvars32.bat when it opens.
Compiling the code produces an executable file named First.exe , which you can run from the
command line or from Windows Explorer like any other executable. Give it a try:

csc First.cs

Microsoft (R) Visual C# Compiler version 9.00.20404
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

First.exe
This isn’t at all like Java!
Well, maybe that message isn ’ t quite true! This program has some fairly fundamental similarities to Java,
although there are one or two points (such as the capitalized Main() function) to catch the unwary
Java or C++ developer. Let ’ s look more closely at what ’ s going on in the code.

A Closer Look

First, a few general comments about C# syntax. In C#, as in other C - style languages, most statements end
in a semicolon ( ; ) and can continue over multiple lines without needing a continuation character (such
as the underscore in Visual Basic). Statements can be joined into blocks using curly braces ( {} ). Single -
line comments begin with two forward slash characters ( // ), and multiline comments begin with a slash
and an asterisk ( /* ) and end with the same combination reversed ( */ ). In these aspects, C# is identical to
C++ and Java but different from Visual Basic. It is the semicolons and curly braces that give C# code such
a different visual appearance from Visual Basic code. If your background is predominantly Visual Basic,
take extra care to remember the semicolon at the end of every statement. Omitting this is usually the
biggest single cause of compilation errors among developers new to C - style languages. Another thing to
remember is that C# is case sensitive. That means that variables named myVar and MyVar are two
different variables.
The first few lines in the previous code example have to do with namespaces (mentioned later in this
chapter), which are a way to group together associated classes. This concept will be familiar to Java and
C++ developers but may be new to Visual Basic 6 developers. C# namespaces are basically the same
as C++ namespaces or, equivalently, Java packages, but there is no comparable concept in Visual Basic 6.
The namespace keyword declares the namespace your class should be associated with. All code within
the braces that follow it is regarded as being within that namespace. The using statement specifies a
namespace that the compiler should look at to find any classes that are referenced in your code but that
aren ’ t defined in the current namespace. This serves the same purpose as the import statement in Java
and the using namespace statement in C++.

using System;
  namespace CSharp.Basics
    {

The reason for the presence of the using statement in the First.cs file is that you are going to use a
library class, System.Console . The using System statement allows you to refer to this class simply as
Console (and similarly for any other classes in the System namespace). The standard System
namespace is where the most commonly used .NET types reside. It is important to realize that

everything you do in C# depends on the .NET base classes. In this case, you are using the Console class
within the System namespace in order to write to the console window. C# has no built - in keywords of
its own for input or output; it is completely reliant on the .NET classes.
Because almost every C# program uses classes in the System namespace, we will assume that a using
System; statement is present in the file for all code snippets in this chapter.

Next, you declare a class called MyFirstClass . However, because it has been placed in a namespace
called CSharp.Basics , the fully qualified name of this class is CSharp.Basics

.MyFirstCSharpClass :
      class MyFirstCSharpClass
       {

As in Java, all C# code must be contained within a class. Classes in C# are similar to classes in Java and
C++, and very roughly comparable to class modules in Visual Basic 6. The class declaration consists of
the class keyword, followed by the class name and a pair of curly braces. All code associated with the
class should be placed between these braces.
Next, you declare a method called Main() . Every C# executable (such as console applications, Windows
applications, and Windows services) must have an entry point — the Main() method (note the capital M ):

     static void Main()
          {

The method is called when the program is started, like the main() function in C++ or Java, or Sub
Main() in a Visual Basic 6 module. This method must return either nothing ( void ) or an integer ( int ).
A C# method corresponds to a method in C++ and Java (sometimes referred to in C++ as a member
function). It also corresponds to either a Visual Basic Function or a Visual Basic Sub , depending on
whether the method returns anything (unlike Visual Basic, C# makes no conceptual distinction between
functions and subroutines).
Note the format of method definitions in C#:

       [modifiers] return_type MethodName([parameters])
      {
             // Method body. NB. This code block is pseudo-code.
       }

Here, the first square brackets represent certain optional keywords. Modifiers are used to specify certain
features of the method you are defining, such as where the method can be called from. In this case, you
have two modifiers: public and static . The public modifier means that the method can be accessed
from anywhere, so it can be called from outside your class. This is the same meaning as public in C++
and Java, and Public in Visual Basic. The static modifier indicates that the method does not operate
on a specific instance of your class and therefore is called without first instantiating the class. This is
important because you are creating an executable rather than a class library. Once again, this has the
same meaning as the static keyword in C++ and Java, though in this case there is no Visual Basic
equivalent (the Static keyword in Visual Basic has a different meaning). You set the return type to
void , and in the example, you don ’ t include any parameters.
Finally, we come to the code statements themselves:

                              Console.WriteLine(“This isn’t at all like Java!”);
                            Console.ReadLine();
                             return;

In this case, you simply call the WriteLine() method of the System.Console class to write a line of
text to the console window. WriteLine() is a static method, so you don ’ t need to instantiate a
Console object before calling it.

Console.ReadLine() reads user input. Adding this line forces the application to wait for the carriage
return key to be pressed before the application exits, and, in the case of Visual Studio 2008, the console
window disappears.
You then call return to exit from the method (also, because this is the Main() method, you exit the
program as well.). You specified void in your method header, so you don ’ t return any values. The return
statement is equivalent to return in C++ and Java, and Exit Sub or Exit Function in Visual Basic.
Now that you have had a taste of basic C# syntax, you are ready for more detail. Because it is virtually
impossible to write any nontrivial program without variables , we will start by looking at variables in C#.



« INDEX - C# sharp professional in 15 days C# Day 1- Basics (part 2) »
Posted on Thursday, February 5th, 2009 at 4:22 pm under Professional C sharp | RSS 2.0 Feed

One Response to “C# Day 1- Basics (part 1)”

  1. INDEX - C# sharp professional in 15 days Says:

    [...] a)C# Day 1- Basics (part 1)(Your First C# Program, Compiling and Running the Program, ) [...]


Post Comment

You must be logged in to post a comment.



ComputerEducationWorld.com All Rights Reserved © RSS | CBSE | Education Boards Of India | What is My IP?