Вы находитесь на странице: 1из 39

Chapter 2

C# Basics

WRITING A PROGRAM
The creation of a simple console
application is given as follows.
o Step 1 Open Visual Studio and create a new console
application. Write the name of the project and start
the project. Figure 2.2 shows the screen that appears
when you go to
o File New Project.
o Step 2 The screen shown in Fig. 2.3 appears when you
click OK. In the Main method, write the following code.
o Console.WriteLine("This moment belongs to
me");
o The statement displays the text This moment
belongs to me, when you run the program.
o Step 3 Run the program either by pressing F5 or by
using the menu bar or toolbar.

PROGRAM STRUCTURE
A C# program contains many
sections.
Documentation
A C# program begins with a optional
documentation section.
This section may contain information
about the program, procedure used,
author, date, time, and so on. It is
important when you are writing a
professional programs.

PROGRAM STRUCTURE
The next part of a program is the using
directive(s).
The using directive qualifies the use of a
namespace so that the namespace need
not be written repeatedly in the program.
The directives help us use the classes,
which in turn help us connect to an access
database.
Examples :
using System;
using System.Collections.Generic;
using System.Linq;

ERROR

METHODS OF WRITING
STATEMENTS
Writing a statement in a single line or
splitting the statement and writing it in
multiple lines is the same as far as C# is
concerned.
Listing 1
static void Main(string[] args)
{
System.Console.WriteLine("Hi there");
Console.ReadKey();
}

Output
Hi there

INTERFACE
An interface contains methods but not
their definitions.
An interface is a blueprint of what is to
be done and does not state not how it is
to be done.
The methods declared in an interface
are defined in the class that implements
it.

The syntax of an interface is as follows:


interface <name of the interface>
{
//Method, properties, index, or
events
}

If an interface student is to have a method


called getdata(), then the following code needs
to be written in the editor:
interface student
{
void getdata()
{
}
}

The interface section of the program contains


various interfaces that the programmer wants
to use in the program.

CLASS DEFINITION
The class definition section of the program
contains the definition of a class.
A class is a real or conceptual entity, which
has importance to problem at hand.
An instance of a class is called an object.
Consequently, the whole concept of objectoriented programming (OOP) originates
from the idea of a class.

NAMESPACES
C# has a lot of predefined classes with
functionalities; examples are input
output, data handling, and networking..
The grouping together of classes
makes organization easy.
For example,
The evaluation of social status, impact of
education, and upliftment of a section of
society may be under
Different departments, but all the departments
come under the department of social welfare

OUTPUT
The output is essential in a program as it is
required both in taking input from the user
and displaying the output.
In C#, output is displayed by using the
Console.WriteLine() method.
The WriteLine() method is in the class
Console.
For example, Console.WriteLine ("Hi");
displays Hi. Console.Write() method can
be used if it is not required to display the
statement in a new line. Readers

INPUT
In C#, every input is taken as a string.
The string, in turn, is converted into the
requisite data type.
For example, if the user is asked to enter
a number, which is to be inserted into an
integer variable, then the following
statement performs the requisite task:
Console.WriteLine("Enter the first
number\t:");
number1 = int.Parse(Console.ReadLine());

The whole statement, however, needs to be


placed in the try block, as the value entered by
the user may not be an integer.
It is enough to remember that any integer input
has to be placed in a try block and with every
try block there has to be a catch block, which
handles the exceptions.
int number1;
try
{
Console.WriteLine("Enter the first number\t:");
number1 = int.Parse(Console.ReadLine());
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine("Error" + e.ToString());
Console.ReadKey();
}

MAIN METHOD
The class is contained in a namespace whose
name is the same as that of the program.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BasicProgram1
{
class Program
{
static void Main(string[] args) {
System.Console.WriteLine("Hi there");
Console.ReadKey();
}
}
}

CONCEPT OF Main
METHOD
When a program is executed, the first method that
runs is Main.
In order to call Main, an instance of the class in
which Main is called has to be made if the method
is not static.
Static methods are those methods that have only
one copy.
They can be called by writing the name of the
class followed by the name of the method, thus
making things easy for the compiler.

In general, the return type of Main is void, as it


does not return anything.
However, in some cases, the Main method can
also return a value.
For example, assume that the requirement of
the project in question is that Main should
return 0 on successful completion. For this to
happen, the return type of Main should be int.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyConsoleApplication
{
class Program
{
static int Main(string[] args)
{

int number1;
try
{
Console.WriteLine("Enter the number\t:");
number1 = int.Parse(Console.ReadLine());
Console.WriteLine("You
have
entered"
+
number1.ToString());
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine("Error" + e.ToString());
Console.ReadKey();
}
return 0;
}
}

MULTIPLE Main
METHODS IN A
PROGRAM
It is possible to have a Main in each class.

In such cases, so as to run a particular


Main, one needs to make some changes
in the properties of the project.
For example, in the next program, the
Main of Program class runs when the
program is executed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BasicProgram1
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Hi there");
Console.ReadKey();
}
}
}
class ABC {
static void Main(string[] args)

{
System.Console.WriteLine("Hi");
Console.ReadKey();
}
}

It should be set equal to the name of the class


whose Main is required to run.
In order to make the Main of class ABC run
when the program is executed, the name of
the startup object should be changed in the
properties of the program

USING SPECIFIC
FUNCTIONS
At times, it becomes essential to use
mathematical functions or the functions
defined in other namespaces.
In order to do so, the using directive must be
written at the beginning of the program to
include the namespace whose function is to be
used in the program or the method should be
called by qualifying the name of the
namespace as well.

Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyConsoleApplication
{
class Program
{
static void Main(string[] args)
{
int number1, number2;
double result;

try
{
Console.WriteLine("Enter the first number\t:");
number1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the second
number\t:");
number2 = int.Parse(Console.ReadLine());
result = Math.Sqrt((1.0 * number2) / number1);
Console.WriteLine("The result is" +
result.ToString());
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine("Error" + e.ToString());
Console.ReadKey();
}
}
}
}

COMMENTS
Comments are the statements that are not
executed when the program runs.
They are important as far as documentation is concerned
and are essential to understand the program.

It may be noted that a project is handled not by a


single person but by a team.
Comments are written in two ways:
1. Single-line comments
2. Multiple-line comments
It may be stated that comments are not
considered in software metrics such as lines of
code (LOC). However, this does not diminish their
importance.

SINGLE-LINE COMMENTS
Single-line comments are generally preceded
by //, as shown in the following listing.
Example
//Using directives [ Single-line comment]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//namespace [->Single-line comment]
namespace MyConsoleApplication
{..

MULTIPLE-LINE
COMMENTS
At times, the explanation of some of the
methods might take more than one line.
The comment is preceded by a /* and
ends with a */.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*namespace
The name is same as that of the
program*/

COMMAND LINE
ARGUMENTS
The arguments given in Main are stored in
the array args.
When command line arguments are given,
these arguments can be handled as
normal array elements.
However, it may be stated that a simple
for loop is capable of traversing through
the array

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyConsoleApplication
{
class Program
{
static int Main(string[] args)
{
for(int i=0;i<args.Length;i++)
{
Console.WriteLine("Argument" + args[i]);
}
Console.ReadKey();
return 0;
}
}
}

The command line arguments can be


given in the Debug tab of the
properties of the project. In
Order to do so, right click on the
name of the namespace in Solution
Explorer and enter the command line
arguments in Start Options.
The output of the program will be as
follows:

COMPILATION PROCESS
The process of compilation has five
main steps, namely lexical analysis,
syntactic analysis, semantic
analysis, intermediate code
generation, and code generation.
The semantic analysis segregates the
program into tokens. These tokens are
identified by the reduced deterministic
finite acceptor.

COMPILATION PROCESS
Lets take an example of an identifier
which starts with a letter and is
followed by any number of letters or
digits:
The regular expression of an identifier
will be l(l + d)*, where l is a
letter and d is a digit.
This regular expression is converted
into a non-deterministic finite
acceptor.

The steps to convert the regular expression into a


deterministic finite acceptor are as follows:
In the first step, the non-deterministic finite
acceptor for (l + d) is made. Here, l and d can be
accepted by the automata by two parallel paths.
This is followed by the formation of the nondeterministic finite acceptor for (l + d)*. Here, *
denotes repetition.
From the second symbol onwards, an identifier may
have any number of letters or digits; therefore, the
initial and the final states of the automata are
connected via a null move. That is, one can go from
the initial to the final state without giving any input.
This step is followed by the formation of automata
l(l + d)*.
In the next step, this automata is converted into a
deterministic finite acceptor.

It is an acceptor as it accepts or rejects. It tells us


whether the input string is an identifier or not.
This process is called lexical analysis. It may be
noted that most of the common errors are
reported by this phase of the compiler.
This step is followed by the syntactic and
semantic analyses. The syntactic analysis checks
the syntax, whereas the semantic analysis
checks the semantics and interprets the meaning
of the construct.
The intermediate code generation generates the
intermediate code, which is a step towards the
final machine level code generation..

The error handling mechanism is


necessary at every phase of the
compilation process.
The following are some instances that
result in an error:
1. Misspelt Keyword
It is the job of a lexical analyser to check whether a
keyword has been spelt correctly. It is done
with the help of a deterministic finite acceptor as
explained earlier.
2. Syntactic Error
An example of syntactic error is the absence of
closing parenthesis in an if condition. The
lexical analyser identifies such errors with the help of
parse trees.
3. Incompatible Operands to an Operator
The intermediate code generator identifies this type
of errors. Such errors become all the more
important in C# as it intends to overcome such
shortcomings in C and C++.

4. Multiple Declarations of an Identifier


The bookkeeping routine helps identifying such errors.
There can be many more sources of errors. When a
program is compiled, the errors will be shown in the
error list. This displays the line number, a brief
description of the error, and the error code. The
screenshot given in the following figure depicts the
error in an error pane.

POINTS TO REMEMBER
Main method section is the most
important and mandatory component of
a C# program.
Main method in C# is public, is static,
and has return type void.
There can be more than one Main
method in C# program.
In order to carry out specialized
mathematical tasks, the program should
have System.Math namespace.

POINTS TO REMEMBER
Comments are not executed when program
runs.
The command line arguments can be given in
the Debug tab of the properties of the project.
The process of compilation has five main
steps, namely lexical analysis, syntactic
analysis, semantic analysis, intermediate code
generation, and code generation.