Basic Programming using CSharp
Basic Programming using CSharp
Objective:
In this lesson, we will learn basic computer programming using C#. Here, we will familiar with
C# syntax and anatomy of a C# program.
Prerequisite:
Participants must have basic programming concept in any programming language.
Topics to be discussed:
In four (4) sections of this lesson, we will learn followings topics. In every section, we have
several practices to be solved.
o Hello World in C#
o What is IDE
o Familiarization of Visual Studio
o Console Application
o Desktop Application
Working with Data Types, Conditional statement
o for loop
o while loop
o do while
o continue & break
1
Pretest & Posttest questions:
1. C# is strongly or weakly typed language?
2. True or False: C# is case sensitive.
3. What is IDE?
4. Write down four data types of C# language
5. Write the differences between implicit and explicit conversion.
6. What kind of problem you can solve using conditional statement (if-then-else)
7. Why do you need looping?
2
Understanding C# program’s basic anatomy
Here, we will create a very small console application. This application will show “Hello World”
into the console (display terminal).
Steps:
1. Start Microsoft Visual Studio 2013
2. Click File>New>Project or, Shortcut Ctrl+Shift+N
3
4. Write appropriate name in ‘Name’ box, change the location of your project directory by
clicking the ‘Browse’ button
5. Click ‘Ok’ button
6. You will see the following code
using System;
using [Link];
using [Link];
using [Link];
namespace WalkThrough1
{
class Program
{
static void Main(string[] args)
{
}
}
}
7. Now write the following code snippet inside the main method
[Link]("Hello world");
[Link]();
Now we will create a very simple desktop application. In this application, user will click on a
button ‘Show’ and a messagebox (a small window) will appear displaying ‘Hello World’.
Steps:
1. Start Microsoft Visual Studio 2013
2. Click File>New>Project
4
3. Select Windows>Windows Forms Application
4. Give an appropriate name and others as the previous walkthrough
5. Click ‘Ok’ button
6. Now drag and drop a button from toolbox situated at the left side of your development
window .(if it is not appeared there, Click View>ToolBox)
7. Click on the button
8. Change the Text Property of the button into ‘Show’
5
9. Double click on the button of the form and write the following code snippet
private void button1_Click(object sender, EventArgs e)
{
[Link]("Hello World");
}
10. Now run the application by clicking on the debug button or pressing F5
11. Click on the ‘Show’ button of the running application
12. A messagebox will appear. You will get the following picture
6
Well done!!! We have completed the Hello World program in C#. Let’s see the details of
Visual Studio 2013, an Integrated Development Environment:
Visual Studio
Visual Studio provides some features to its users. Some of these are:
Code editing
Debugging the code
Designing the User Interface
Some helping tools
Extensibility
Visual Studio has some built-in language compilers integrated in it. The main languages are C#
and Visual Basic. But one can create any application in another language such as J#, C++ etc.
7
Templates
Visual studio project and item templates provide reusable and customizable project and item
stubs that accelerates the development process, removing the need to create new projects and
items from scratch.
Depending on the instance of the Visual Studio, generally there are 2 types of templates we can
see. They are:
Project templates
Windows
Web
Smart Device
Office
Database
Reporting
Test
WCF
Workflow
Item templates
General
Web
Script
Steps:
1. Start Microsoft Visual Studio 2013
2. Click File>New>Project or, Shortcut Ctrl+Shift+N
8
Figure: Project Template
Steps:
1. Start Microsoft Visual Studio 2013
2. Click File>New>File or, Shortcut key Ctrl+N
9
Figure: Item Template
Class library:
Like all other programming language, C# also follows some rules. At first, a sample program
needs some system library classes.
For example:
using [Link];
If this is not written at the beginning of a class structure, one can’t use the regular expression
functionalities under that class.
Namespace:
A project can have multiple classes. To organize these classes, multiple folders can be created.
The conceptual hierarchy is called the namespace. We will discuss Namespace in details in
another session.
10
For example:
namespace AnatomyOfCSharpClass
This is a sample namespace of a project.
Main Method:
Main() method is the entry point of any kind of high level language. C# is not indifferent from
that. A C# project (Desptop or Console i.e. executable) must have a Main() method. The code
written for a main method is:
Console Application
Starting with console applications is a better starting because developers can easily understand
everying.
A user typically interacts with a console application using only a keyboard and display screen, as
opposed to GUI applications, which normally require the use of a mouse or other pointing
device. Many console applications such as command line interpreters are command line tools,
but numerous Text User Interface (TUI) programs also exist.
Desktop Application
An application (desktop) is a computer program designed to help people perform a certain type
of work. In a desktop application users can interact with the application via both keyboard and
mouse.
11
Working with Data Types, Conditional statement
In this section, you will be familiar with data types, expression, and conditional statements in C #syntax.
Data Types:
When we instruct a machine to execute some operation, the machine changes the high level language
(which we are sending) into machine code (sequence of 1s and 0s). The instruction we are sending also
contains data on which the operation will be executed.
But not all data should contain the same amount of memory nor do the same types of operations. So,
different sets of data have different size and perform different types of operations. And they are not
interpreted in the same way.
So, programmer needs to tell the system before-hand, the type of numbers or characters he is using in his
instruction (coding). These types are called Data Types. There are many data types in C# language.
Different types of predefined data types allocated different amount of memory and performs different
types of operation. The following data table lists the predefined data types and describes the data that they
are designed to store.
User defined data types are composed of different combination of predefined data types. Sometimes a
user defined data type contains another user defined data type in it. A user defined data type can also
perform some operations and the definition of the operation will be stated into the type definition.
To use a data in our program, we have to follow some specified way and use some specific keywords that
are defined by the language creators.
In this tutorial, we will follow the naming convention which has been described in an excel sheet. Find it
in attachment of this [Link]: Naming convention file.
In the above two lines, I have declared two variables and initialized these with values. Even you can
declare a variable without initializing it.
int numberOfItems;
double priceWithVAT;
But the following two lines will not compiled because I am trying to use numberOfItems as a parameter
of WriteLine method without initializing it. It’s not possible to use a variable without initializing it.
int numberOfItems;
[Link](numberOfItems);
You will get an error. Compiler can’t convert a double value to decimal type.
or
As stated above, a string variable contains a sequence of alphanumeric characters. We can declare a string
variable like other types of variable. Example:
string name;
string firstName = "Masud Rana";
Escape characters:
Escape characters are used when we want to set a run time meaning of a part of a string. Example:
string greetings = "Hello everyone.\nWelcome to OOP Class.";
Verbatim characters:
A verbatim string is a string that is interpreted by the compiler exactly as it is written, which means that
even if the string spans multiple lines or includes escape characters, these are not interpreted by the
compiler and they are included with the output. The only exception is the quotation mark character, which
must be escaped so that the compiler can recognize where the string ends. Example:
As you can see, verbatim is indicated with an ‘@’ sign at the beginning of a string. If you want to use a
quotation mark inside a verbatim string, you must escape it by using another set of quotation marks.
Example:
A constant is a variable whose value remains constant. Constants are useful in situations where the value
that you are using has meaning and is a fixed number, such as pi, the radius of the earth, or a tax rate.
Example:
const int radiusOfEarth = 6378;
As you can see, constant variable starts with the keyword ‘const’ at the declaration, or initialization.
14
Sometimes we have to change the data that we are using. Sometimes this change may change the value of
the data or sometimes it just changes the memory space allocated by that data. This change is called data
type conversion. Data type is converted in two ways. They are:
a. Implicit conversion
b. Explicit conversion
Implicit conversion:
An implicit conversion converts data automatically without losing any data. Normally, data types can
implicitly converted into the data types those contain more memory space. Example:
short firstNumber = 65;
long secondNumber = firstNumber;
Explicit conversion:
An explicit conversion convert data that are automatically can’t be converted. It may converts data from
bigger size to smaller size or converts data from one type into totally different type. Example:
short firstNumber = 65;
long secondNumber = firstNumber; //Implicit conversion
short thirdNumber = (short)secondNumber; //Explicit conversion
[Link](thirdNumber); //outputs 65
char a = (char)firstNumber; //Explicit conversion
[Link](a); //outputs A
We can use some built in functions those are provided with C#.
a. Convert class:
A convert class contains numerous methods those can change one data type into another type. It
is another implementation of explicit conversion.
Example:
int number = 65;
char character = [Link](number); //Conversion using System's
Class
[Link](character); //Output: A
b. ToString() method:
A ToString() method converts any kind of data type into String type. It doesn’t change the
internal value of that data.
Example:
char character = [Link](65); //Conversion using System's
Class
string numberString = (65).ToString();
[Link](character); //Output: A
15
[Link](numberString); //Output(value is in String form):
65
Download Purchase Ticket from attachment of this lesson. Run the the sample and see the code
behind the form as follows:
public PurchaseTicketUI()
{
InitializeComponent();
}
First of all, see the name of every control, we have followed the naming convention mention in
attachment file.
I also declare variables of int, double and string data types. We will discuss the details of data
types later. Here, I use ToInt16() method of Convert class to convert the text data into integer
value.
16
Practice : Create a desktop application like the following figure.
Features:
After clicking on the save button, all of the information of the textbox will be
disappeared.
Button names are self descriptive. Relevant information will be shown in a
messagebox when a button is clicked.
17
Create a calculator which will take two numbers in two different textboxes. It has four buttons
(Add, Subtract, Multiply, Divide). Calculated result will be showed in the result TextBox when
the button is clicked.
Expressions:
An expression is a sequence of operators and operands. An operator is a concise symbol that indicates the
action that you want to occur in your expression. An operand is the value on which an operation is
performed. An operator is specifically designed to produce a new value from the value that is being
operated on.
Example:
Conditional operator: &&,||
Mathematical operator: +
Conditional statements:
A conditional statement allows you to control the flow of your application by selecting the statement that
is executed, based on the value of a Boolean expression. Syntax:
a. If(boolean-expression) statement
b. If(boolean-expression) statement1
else statement2
c. If(boolean-expression) statement1
else if(boolean-expression) statement2
else statement3
Example:
bool condition;
if (condition == true)
18
{
[Link]("condition is true");
}
else if (condition == false)
{
[Link]("condition is false");
}
else
{
[Link]("unknown value");
}
Steps:
1. Create a desktop application
2. Design the user interface like the following figure
Download the sample from attachment. Walkthrough: Working with conditional statement.
Write a program to calculate the bonus on employee salary. If the salary amount is more than 10000,
bonus will be 5%. If it is greater than or equal 8000 and less than or equal to 10000, bonus will be 6%.
Otherwise bonus will be 7%.
Iteration Statement
C# provides several looping mechanisms, which enable you to execute a block of code repeatedly
until a certain condition is met. In each case, a statement is executed until a Boolean expression
returns true. By using these looping mechanisms, you can avoid typing the same line of code over
and over.
a. For loop:
A for loop must have 3 basic parameters. It must have a loop initializer value, a loop ending value
and also an increment/decrement operator. These 3 types of value can be written in any part of the for
loop block. But generally, these are written in the heading part of the loop.
Example:
for (int count = 0; count < endingValue; count++)
{
sum += count;
}
b. While loop:
While loop first checks a boolean expression and then enters into the code block. This loop runs until
that expression turns into false.
Example:
while (condition == true)
{
sum += count++;
if (count > 50)
{
condition = false;
}
}
20
c. Do-While loop:
Do while loop first executes the whole code block one time and then checks the boolean expression.
If the expression is false, this loop quit execution and go to the next statements. Otherwise, it runs
until it finds the boolean expression false. Example:
do
{
sum += count++;
}while (count < 10);
Continue:
To continue the loop operation without executing the rest of the statements on the block, continue
keyword is used.
Break:
Break keyword is used to break the loop. Example:
User will input a number and click Add button then from 0 to that number will be added in a
listview/listbox control. After that user will select a number from the listview/listbox and click Show
button, selected number will be shown in messagebox.
21
Find the solution in attachment. Walkthrough: Working with iteration statement
In this program you will calculate interest amount on balance (principal amount) after certain duration.
See the following UI which will help you to understand what user wants from you.
Data:
BRAC: 6%
DBBL: 7%
HSBC: 8%
23