0% found this document useful (0 votes)
2 views23 pages

Basic Programming using CSharp

This document provides an introduction to basic programming using C#, covering essential topics such as C# syntax, data types, conditional statements, and iteration statements. It includes practical exercises for creating console and desktop applications, specifically a 'Hello World' program, and explains the use of Visual Studio as an Integrated Development Environment (IDE). Additionally, it discusses data type conversion and provides examples of user-defined data types and constants.

Uploaded by

NiZAM UDDIN
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views23 pages

Basic Programming using CSharp

This document provides an introduction to basic programming using C#, covering essential topics such as C# syntax, data types, conditional statements, and iteration statements. It includes practical exercises for creating console and desktop applications, specifically a 'Hello World' program, and explains the use of Visual Studio as an Integrated Development Environment (IDE). Additionally, it discusses data type conversion and provides examples of user-defined data types and constants.

Uploaded by

NiZAM UDDIN
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Basic Programming using C#

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.

 Understanding C# program’s basic anatomy

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 Basic data types in C#


o Implicit and explicit conversion
o Expression
o Conditional statement
 Iteration 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

In this section, we write ‘Hello World’ program using C#.

Writing ‘Hello World’ as a console application

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

You will see the following window.

Figure: New Project Creation Templates

3. Select Windows>Console Application

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]();

8. Now Press F5 or Click on the Debug button

Figure: Debug Icon

9. You will see the output given below

Writing ‘Hello World’ Program as a desktop application

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

You will get the following picture in your window

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’

This will looks like the following picture.

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

Microsoft Visual Studio is an Integrated Development Environment (IDE) created by Microsoft


Corporation for Application Development. This IDE is used to develop console and windows
applications run able only in Windows Platform. It is used to develop web application also.
Visual Studio 2013 is one of the versions of Visual Studio. Some other versions are Visual
Studio 2005 and Visual Studio 2010.

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

Walkthrough 1: Visual Studio Project Template Familiarization

Now, we will view some templates of Visual Studio 2013.

Steps:
1. Start Microsoft Visual Studio 2013
2. Click File>New>Project or, Shortcut Ctrl+Shift+N

You will see the following window.

8
Figure: Project Template

Walkthrough 2: Visual Studio Item Template Familiarization

We will now view some item templates of Visual Studio 2013.

Steps:
1. Start Microsoft Visual Studio 2013
2. Click File>New>File or, Shortcut key Ctrl+N

You will see the following window.

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:

static void Main(string[] args)

When we run an application, it starts from Main() method.

Console Application

A console application is a computer program designed to be used via a text-only computer


interface, such as a text terminal, the command line interface of some operating systems (Unix,
DOS, etc.) or the text-based interface included with some Graphical User Interface (GUI)
operating systems, such as the Win32 console in Microsoft Windows.

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.

There are two categories of Data Type.


i. Predefined (Primitive) Data Types
ii. User defined Data Types

Predefined Data Types:

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.

Type Name Definition Byte


Byte Integer (0 to 255) 1
Sbyte Integer(-127 to 128) 1
Short Integer (-32768 to 32767) 2
Ushort Integer (0 to 65535) 2
int Integer (-2147483648 to 2147483648) 4
Uint Integer (0 to 4294967295) 4
Long Integer (-9223372036854775808 to - 8
9223372036854775808)
Ulong Integer (0 to 18446744073709551615) 8
Bool Boolean value(true or false) 1
Float Single-precision floating point value 4
double Double-precision floating point value 8
Decimal Precise decimal value to 28 significant digits 16
12
Object Base type of all other types N/A
Char Single Unicode character 2
String An unlimited sequence of Unicode characters N/A

User-defined Data Types:

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.

Working with data types:

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.

int numberOfItems = 100;


double priceWithVAT = 100.50;

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);

Now try this:

decimal priceWithVAT = 100.50;

You will get an error. Compiler can’t convert a double value to decimal type.

decimal priceWithVAT = 100.50M;

or

decimal priceWithVAT = [Link](100.50);


13
or even

decimal priceWithVAT = (decimal)100.50;

Data Type: String

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:

string address = @"C:\Software\Books\Beginning”;

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:

string greetings = @"""Hello everyone"".said the trainer.";

Data Type: Constants

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.

Data Type Conversion:

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

Walkthrough : ‘Purchase Ticket’ as a desktop application

Download Purchase Ticket from attachment of this lesson. Run the the sample and see the code
behind the form as follows:

public partial class PurchaseTicketUI : Form


{
private int numberOfTickets = 0;
private double unitPrice = 10;
private string customerName = "";
private double totalPrice = 0;

public PurchaseTicketUI()
{
InitializeComponent();
}

private void totalPriceButton_Click(object sender, EventArgs e)


{
numberOfTickets = Convert.ToInt16([Link]);
customerName = [Link];
totalPrice = unitPrice * numberOfTickets;
[Link](customerName + ", Please Pay " + totalPrice + "
Taka to Purchase " + numberOfTickets + " Ticket(s)");
}

private void detailsButton_Click(object sender, EventArgs e)


{
[Link]("Customer Name: " + customerName + "\nUnit Price:
" + unitPrice + "\n Total Price: " + totalPrice);
}
}

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.

Download the solution from attachment: Practice: Personal Information

Practice: Simple Calculator

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.

Find the solution in attachment. Practice: Simple Calculator

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");
}

d. If((boolean-expression) operator (boolean-expression)) statement


Example:
if (scoreOutOfHundred >= 60 && scoreOutOfHundred < 80)
{
return "A+";
}
e. (boolean-expression) ? (statement1) : (statement2)
Example:
bool value = true;
[Link](value ? "True Value" : "False Value");

Walkthrough: Working with conditional statements

Steps:
1. Create a desktop application
2. Design the user interface like the following figure

3. Double click on the button


4. Write down the code snippet in the block
string planetName=[Link];
if(planetName=="Planet")
{
[Link]("It is in 3rd position");
}
else if(planetName=="Saturn")
{
[Link]("It is in 6th position");
}
else if(planetName=="Mars")
{
19
[Link]("It is in 4th position");
}
else
{
[Link]("I don’t know”);
}
5. Build the solution and run it

Download the sample from attachment. Walkthrough: Working with conditional statement.

Practice: Bonus Calculator

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%.

No solution is given for this practice.

 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:

for (int count = 0; count < MAXIMUM_VALUE; count++)


{
if (count == expectedValue)
{
break;
}
else
{
continue;
}
}

Walkthrough: Working with iteration statements

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

Practice: Interest Calculator

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%

No solution is given for this practice.


22
More Questions of this lesson:

1. What is the difference between continue and break?


2. What is the difference between do-while and while loop

23

You might also like