Chapter One-Introduction To C#

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 95

Wollo University

College of Informatics
Department of computer science
Window Programming(CoSc4151)
Chapter 1: Introduction to C#
Introduction to C#
Prepared by: kibrom
Haftu(MSc)
Kombolcha
Table of Contents

 Introduction to C#
 C# Implementation
 Microsoft.NET Platform and Its Architecture
 Console application development
What is Computer Programming?

Computer programming: creating a sequence


of instructions to enable the computer to do
something.
Definition by Google
Programming Phases

 Specification : Define a task/problem.


 Design: Plan your solution
 Find suitable algorithm to solve it
 Find suitable data structures to use
 Implementation: Write code.
 Testing and Debugging: Fix program error (bugs).
 Deployment: Make your customer happy.
What is "C#"?

 Programming language

 A syntax that allow to give instructions to the computer

 C# features:

 New cutting edge language

 Extremely powerful

 Easy to learn

 Easy to read and understand

 Object-oriented
What You Need to Program using C#?

 Knowledge of a programming language


 C#
 Task to solve
 Development environment
 Visual Studio
 Set of useful standard classes
 Microsoft .NET Framework
C# implementation

C# can be implemented as :
 Visual Programming
 Event-Driven Programming
 Object-Oriented Programming
 Internet and Web Programming
Visual Programming
 In addition to writing program statements to build
portions of apps using Visual Studio’s graphical user
interface (GUI) able conveniently drag and drop
predefined objects
 Example buttons and textboxes into place on your
screen, and label and resize them.
Event-Driven Programming
 Can write programs that respond to user-initiated
events such as:
 mouse clicks, keystrokes, timer expirations and
touches and finger swipes—gestures that are
widely used on smart phones and tablets.
Object-Oriented Programming
 C# can model a programming where programs
are organized around objects and data rather
than action and logic.
Internet and Web Programming
 Today’s apps can be written with the aim of
communicating among the world’s computers.
this is the focus of Microsoft’s .NET strategy.
you’ll build web-based apps with C# and
Microsoft’s ASP.NET technology.
What is .NET Framework?
What is .NET Framework?

 Environment for execution of .NET programs


 Powerful library of classes
 Programming model
 Common execution engine for many programming
languages
 C#, Visual Basic .NET, Visual C++ ... and many
others
Inside .NET Framework
 Building blocks of .NET Framework
Components of .NET Framework

 Common Language Runtime (CLR)


 Common Language specification
 NET Framework Class Library
 Common Type System
 Windows Form
 ADO.NET
 LINQ – language integration Query
 ASP.NET
Common Language Runtime (CLR)
 Managed execution environment
 Executes .NET applications
 Controls
CLR
the execution process
 Automatic memory management (garbage collection)
 Programming languages integration
 Multiple versions support for assemblies
 Integrated type safety and security
Framework Class Library (FCL)
 .Net Framework has thousands of valuable prebuilt classes.
 Provides basic functionality to developers:

 Console applications

 Windows Forms GUI applications

 Web applications (dynamic Web sites)

 Web services, communication and workflow

 Server & desktop applications

 Applications for mobile devices


Common Language specification

 Contains the specifications for .Net supported

languages and implementations of language

integration.

Common Type System


 it provides guidelines for declaring, using and

managing types at run time and cross language

communication.
Windows Form
 it contains the graphical representation of any window
displayed in the application.

ADO.NET
 an acronym for Advanced Data Objects.
 allows connection to data sources for retrieving,
manipulating and updating data from database by
providing access to data sources like SQL server ,XML
etc.
LINQ – language integration Query
 a Microsoft programming model and methodology that
essentially adds formal query capabilities into Microsoft .
NET-based programming languages.
 it imparts data querying capabilities to .Net languages using a
syntax which is similar to the traditional query language SQL

ASP.NET
 a technology for developing, deploying, and running Web
applications by having access to classes in the .NET
Framework using HTML, CSS and JavaScript.
What is Visual Studio?
Visual Studio

 Integrated Development Environment (IDE)


 Development tool that helps us to:
 Write code
 Design user interface
 Compile code
 Execute / test / debug applications
 Browse the help
 Manage project's files
 Single tool for:
 Writing code in many languages (C#, VB, …)
 Using different technologies (Web, WPF, …)
 For different platforms (.NET CF, Silverlight, …)
 Full integration of most development activities
(coding, compiling, testing, debugging,
deployment, version control, ...)
 Very easy to use!
Applications in C# Program

C# allows us to write programs like:


 Console based application
 Windows Forms Application
 Web Forms Application
Console based application
 application programs that are easy to develop and perform all their
input and output at the command line with access to three basic
data streams: standard input, standard output and standard error.
 The program structure of a console application facilitates a
sequential, conditional and loop execution flow between
statements.
 Designed for providing no user interface interaction such as
samples for learning C# language features and command line
utility programs, and automated testing which can reduce
automation implementation resources.
C# - Program Structure
27

A C# program consists of the following parts:


 Namespace declaration
 A class
 Class methods
 Class attributes
 A Main method
 Statements and Expressions
 Comments
 Let us look at a simple code that prints the words "Hello
World":
28
Include the standard
namespace "System" Define a class called
"HelloCSharp"

using System; Define the


class HelloCSharp Main()
{ method – the
program entry
static void Main() point
{
Console.WriteLine("HellO World");
}
} Print a text on the console by
calling the method
"WriteLine" of the class
"Console"
Let us look at the various parts of the given program:
30
 using System; - the using keyword is used to
include the System namespace in the program. A
program generally has multiple using statements.
 namespace declaration. A namespace is a
collection of classes. The HelloWorldApplication
namespace contains the class HelloWorld.
 class declaration, the class HelloWorld contains
31
the data and method definitions that your program
uses. Classes generally contain multiple methods.
Methods define the behavior of the class. However,
the HelloWorld class has only one method Main.
 the Main method, which is the entry point for all
C# programs. The Main method states what the
class does when executed.
32
 /*...*/ is ignored by the compiler and it is put to add
comments in the program.
 the Main method specifies its behavior with the
statement Console.WriteLine("Hello World");

WriteLine is a method of the Console class defined in


the System namespace. This statement causes the
message "Hello, World!" to be displayed on the
screen.
 Console.ReadKey(); is for the VS.NET Users.
33
This makes the program wait for a key press and it
prevents the screen from running and closing
quickly when the program is launched from Visual
Studio .NET.
It is worth to note the following points:
34

 C# is case sensitive.
 All statements and expression must end with a
semicolon (;).
 The program execution starts at the Main method.
 Unlike Java, program file name could be different
from the class name.
C# Programming Concepts

Variables and Data Types Control Statements


 How Computing Works?  Comparison and Logical

Operators
 What Is a Data Type?
 The if Statement
 Implicit and Explicit
 The if-else Statement
Type Conversions
 Nested if Statements
 What Is a Variable?
Loops  The switch-case Statement
Variables and Data Types

How Computing Works?


Computers are machines that process data
 Data is stored in the computer memory in variables
 Variables have name, data type and value
 Example of variable definition and assignment in
C#

Variable name
Data type int count = 5;

Variable value
What Is a Data Type?
 A data type:
 Is a domain of values of similar characteristics
 Defines the type of information stored in the computer
memory (in a variable)
 Examples:
 Positive integers: 1, 2, 3, …
 Alphabetical characters: a, b, c, …
 Days of week: Monday, Tuesday, …
Data Type Characteristics
 A data type has:
 Name (C# keyword or .NET type)
 Size (how much memory is used)
 Default value
 Example:
 Integer numbers in C#
 Name: int
 Size: 32 bits (4 bytes)
 Default value: 0
What are Integer Types?
 Integer types:
 Represent whole numbers
 May be signed or unsigned
 Have range of values, depending on the size of
memory used
 The default value of integer types is:
 0 – for integer types (short mean 32 bit), except
 0L – for the long type(64 bit representation)
What are Floating-Point Types
 Floating-point types:
 Represent real numbers
 May be signed or unsigned
 Have range of values and different precision depending on the
used memory
 Can behave abnormally in the calculations
 Floating-point types are:
 float: 32-bits, precision of 7 digits
 double: 64-bits, precision of 15-16 digits
 The default value of floating-point types:
 Is 0.0F for the float type

The Boolean Data Type
 The Boolean data type:
 Is declared by the bool keyword

 Has two possible values: true and false

 Is useful in logical expressions

 The default value is false


 Example of boolean variables taking values of true or false:

int a = 1;
int b = 2;

bool greaterAB = (a > b);

Console.WriteLine(greaterAB); // False

bool equalA1 = (a == 1);

Console.WriteLine(equalA1); // True
The Character Data Type
 The character data type:
 Represents symbolic information
 Is declared by the char keyword
 Gives each symbol a corresponding integer code
 Has a '\0' default value
 Takes 16 bits of memory (from U+0000 to U+FFFF)
The String Data Type
 The string data type:
 Represents a sequence of characters
 Is declared by the string keyword
 Has a default value null (no value)
 Strings are enclosed in quotes:
string s = "Microsoft .NET Framework";
 Strings can be concatenated
 Using the + operator
Saying Hello – Example
 Concatenating the two names of a person to obtain his
full name:
string firstName = "Ivan";
string lastName = "Ivanov";
Console.WriteLine("Hello, {0}!\n", firstName);

string fullName = firstName + " " + lastName;


Console.WriteLine("Your full name is {0}.",
fullName);

 NOTE: a space is missing between the two names! We


have to add it manually
The Object Type
 The object type:
 Is declared by the object keyword
 Is the base type of all other types
 Can hold values of any type
 Example of an object variable taking different types
of data:
object dataContainer = 5;
Console.Write("The value of dataContainer is: ");
Console.WriteLine(dataContainer);
dataContainer = "Five";
Console.Write("The value of dataContainer is: ");
Console.WriteLine(dataContainer);
Implicit and Explicit Type Conversions

 Implicit Type Conversion


 Automatic conversion of value of one data type to
value of another data type
 Allowed when no loss of data is possible
 "Larger" types can implicitly take values of smaller "types"
 Example:
int i = 5;
long l = i;
 Explicit type conversion
 Manual conversion of a value of one data type to a
value of another data type
 Allowed only explicitly by (type) operator
 Required when there is a possibility of loss of data or
precision
 Example:

long l = 5;
int i = (int) l;
Type Conversions – Example
 Example of implicit and explicit conversions:
float heightInMeters = 1.74f; // Explicit conversion
double maxHeight = heightInMeters; // Implicit

double minHeight = (double) heightInMeters; // Explicit

float actualHeight = (float) maxHeight; // Explicit

float maxHeightFloat = maxHeight; // Compilation error!

 Note: Explicit conversion may be used even if not


required by the compiler
What Is a Variable?
 A variable is a:
 Placeholder of information that can usually be changed
at run-time
 Variables allow you to:
 Store information
 Retrieve the stored information
 Manipulate the stored information
Variable Characteristics
 A variable has:
 Name
 Type (of stored data)
 Value
 Example:
int counter = 5;
 Name: counter
 Type: int
 Value: 5
Declaring Variables
 When declaring a variable we:
 Specify its type
 Specify its name (called identifier)
 May give it an initial value
 The syntax is the following:
<data_type> <identifier> [= <initialization>];

 Example:
int height = 200;
Identifiers
 Identifiers may consist of:
 Letters (Unicode)
 Digits [0-9]
 Underscore "_"
 Identifiers
 Can begin only with a letter or an underscore
 Cannot be a C# keyword
 Identifiers
 Should have a descriptive name
 It is recommended to use only Latin letters
 Should be neither too long nor too short
 Note:
 In C# small letters are considered different than the capital letters (case
Identifiers – Examples
 Examples of correct identifiers:
int New = 2; // Here N is capital
int _2Pac; // This identifiers begins with _
string поздрав = "Hello"; // Unicode symbols used
// The following is more appropriate:
string greeting = "Hello";
int n = 100; // Undescriptive
int numberOfClients = 100; // Descriptive
// Overdescriptive identifier:
int numberOfPrivateClientOfTheFirm = 100;

 Examples of
int new; // incorrect identifiers:
new is a keyword
int 2Pac; // Cannot begin with a digit
Assigning Values
 Assigning of values to variables
 Is achieved by the = operator
 The = operator has
 Variable identifier on the left
 Value of the corresponding data type on the right
 Could be used in a cascade calling, where assigning is
done from right to left
Assigning Values – Examples
 Assigning Values – Examples
int firstValue = 5;
int secondValue;
int thirdValue;

// Using an already declared variable:


secondValue = firstValue;

// The following cascade calling assigns


// 3 to firstValue and then firstValue
// to thirdValue, so both variables have
// the value 3 as a result:

thirdValue = firstValue = 3; // Avoid this!


Initializing Variables
 Initializing
 Is assigning of initial value
 Must be done before the variable is used!
 Several ways of initializing:
 By using the new keyword
 By using a literal expression
 By referring to an already initialized variable
Initialization – Examples
 Example of some initializations:
// The following would assign the default
// value of the int type to num:
int num = new int(); // num = 0

// This is how we use a literal expression:


float heightInMeters = 1.74f;

// Here we use an already initialized variable:


string greeting = "Hello World!";
string message = greeting;
Control statements
Conditional Statements

Comparison Operators

Example:

bool result = 5 <= 6;


Console.WriteLine(result); // True
Logical Operators

 De Morgan laws
 !!A  A
 !(A || B)  !A && !B
 !(A && B)  !A || !B
if and if-else

Implementing Conditional Logic


The if Statement
 The most simple conditional statement
 Enables you to test for a condition
 Branch to different parts of the code depending on
the result
 The simplest form of an if statement:

if (condition)
{
statements;
}
Condition and Statement
 The condition can be:
 Boolean variable
 Boolean logical expression
 Comparison expression
 The condition cannot be integer variable (like in C /
C++)
 The statement can be:
 Single statement ending with a semicolon
 Block enclosed in braces
How It Works?
 The condition is evaluated
 If it is true, the statement is executed
 If it is false, the statement is skipped
The if Statement – Example
static void Main()
{
Console.WriteLine("Enter two numbers.");

int biggerNumber = int.Parse(Console.ReadLine());


int smallerNumber = int.Parse(Console.ReadLine());

if (smallerNumber > biggerNumber)


{
biggerNumber = smallerNumber;
}
Console.WriteLine("The greater number is: {0}",
biggerNumber);
}
The if-else Statement
 More complex and useful conditional statement
 Executes one branch if the condition is true, and
another if it is false
 The simplest form of an if-else statement:
if (expression)
{
statement1;
}
else
{
statement2;
}
How It Works ?

 The condition is evaluated


 If it is true, the first statement is executed
 If it is false, the second statement is executed
if-else Statement – Example
 Checking a number if it is odd or even
string s = Console.ReadLine();
int number = int.Parse(s);

if (number % 2 == 0)
{
Console.WriteLine("This number is even.");
}
else
{
Console.WriteLine("This number is odd.");
}
Nested if Statements
 if and if-else statements can be nested, i.e.
used inside another if or else statement
 Every else corresponds to its

closest preceding if
Nested if
if (first == second)
Statements – Example
{
Console.WriteLine( "These two numbers are equal.");
}
else
{
if (first > second)
{
Console.WriteLine("The first number is bigger.");
}
else
{
Console.WriteLine("The second is bigger.");
}
}
The switch-case
 Making Several Comparisons at Once
 Selects for execution a statement from a list
depending on the value of the switch expression
switch (day)
{
case 1: Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday"); break;
case 3: Console.WriteLine("Wednesday"); break;
case 4: Console.WriteLine("Thursday"); break;
case 5: Console.WriteLine("Friday"); break;
case 6: Console.WriteLine("Saturday"); break;
case 7: Console.WriteLine("Sunday"); break;
default: Console.WriteLine("Error!"); break;
}
How switch-case Works?
1. The expression is evaluated
2. When one of the constants specified in a case
label is equal to the expression
 The statement that corresponds to that case is
executed
3. If no case is equal to the expression
 If there is default case, it is executed
 Otherwise the control is transferred to the end point
of the switch statement
Loops
 Execute Blocks of Code Multiple Times
 What is a Loop?

 Loops in C#

• while loops
• do … while loops
• for loops
• foreach loops
 Nested loops
What Is Loop?
 A loop is a control statement that allows repeating
execution of a block of statements
 May execute a code block fixed number of times
 May execute a code block while given condition holds
 May execute a code block for each member of a
collection
 Loops that never end are called an infinite loops
Using while(…) Loop
 Repeating a Statement While Given Condition
Holds
 The simplest and most frequently used loop
while (condition)
{
statements;
}

 The repeat condition


 Returns a boolean result of
true or false
 Also called loop condition
while(…) examples
int counter = 0;
while (counter < 10)
{
Console.WriteLine("Number : {0}", counter);
counter++;
}
while(…) examples
 Calculate and print the sum of the first N natural
numbers( Sum 1..N)
Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
int number = 1;
int sum = 1;
Console.Write("The sum 1");
while (number < n)
{
number++;
sum += number ;
Console.Write("+{0}", number);
}
Console.WriteLine(" = {0}", sum);
Prime Number – Example
 Checking whether a number is prime or not
Console.Write("Enter a positive integer number: ");
uint number = uint.Parse(Console.ReadLine());
uint divider = 2;
uint maxDivider = (uint) Math.Sqrt(number);
bool prime = true;
while (prime && (divider <= maxDivider))
{
if (number % divider == 0)
{
prime = false;
}
divider++;
}
Console.WriteLine("Prime? {0}", prime);
Using break Operator to Calculating Factorial

 break operator exits the inner-most loop


static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
// Calculate n! = 1 * 2 * ... * n
int result = 1;
while (true)
{
if(n == 1)
break;
result *= n;
n--;
}
Console.WriteLine("n! = " + result);
}
do { … } while (…) Loop
 Another loop structure is:
do
{
statements;
}
while (condition);
 The block of statements is repeated
 While the boolean loop condition holds
 The loop is executed at least once
Factorial – Example
 Calculating N factorial
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int factorial = 1;

do
{
factorial *= n;
n--;
}
while (n > 0);

Console.WriteLine("n! = " + factorial);


}
Product[N..M] – Example
 Calculating the product of all numbers in the
interval [n..m]:
int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());
int number = n;
decimal product = 1;
do
{
product *= number;
number++;
}
while (number <= m);
Console.WriteLine("product[n..m] = " + product);
For Loops
 The typical for loop syntax is:
for (initialization; test; update)
{
statements;
}
 Consists of
 Initialization statement -
 Boolean test expression
 Update statement
 Loop body block
The Initialization Expression

for (int number = 0; ...; ...)


{
// Can use number here
}
// Cannot use number here

 Executed once, just before the loop is entered


 Like it is out of the loop, before it
 Usually used to declare a counter variable
The Test Expression

for (int number = 0; number < 10; ...)


{
// Can use number here
}
// Cannot use number here
 Evaluated before each iteration of the loop
 If true, the loop body is executed
 If false, the loop body is skipped
 Used as a loop condition
The Update Expression
for (int number = 0; number < 10; number++)
{
// Can use number here
}
// Cannot use number here

 Executed at each iteration after the body of the loop


is finished
 Usually used to update the counter
Simple for Loop – Example
 A simple for-loop to print the numbers 0…9:

for (int number = 0; number < 10; number++)


{
Console.Write(number + " ");
}

 A simple for-loop to calculate n!:


decimal factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
Complex for Loop – Example
 Complex for-loops could have several counter
variables:
for (int i=1, sum=1; i<=128; i=i*2, sum+=i)
{
Console.WriteLine("i={0}, sum={1}", i, sum);
}
 Result:
i=1, sum=1
i=2, sum=3
i=4, sum=7
i=8, sum=15
...
N^M – Example
 Calculating n to power m (denoted as n^m):
static void Main()
{
int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());
decimal result = 1;
for (int i=0; i<m; i++)
{
result *= n;
}
Console.WriteLine("n^m = " + result);
}
foreach Loop
Iteration over a Collection
 The typical foreach loop syntax is:
foreach (Type element in collection)
{
statements;
}
 Iterates over all elements of a collection
 The element is the loop variable that takes sequentially
all collection values
 The collection can be list, array or other group of
elements of the same type
foreach Loop – Example

string[] days = new string[] {


"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
foreach (String day in days)
{
Console.WriteLine(day);
}

 The above loop iterates of the array of days


 The variable day takes all its values
Nested Loops
 Using Loops Inside a Loop
 A composition of loops is called a nested loop
 A loop inside another loop
 Example:
for (initialization; test; update)
{
for (initialization; test; update)
{
statements;
}

}
Triangle – Example
 Print the following triangle:
1
1 2

1 2 3 ... n
int n = int.Parse(Console.ReadLine());
for(int row = 1; row <= n; row++)
{
for(int column = 1; column <= row; column++)
{
Console.Write("{0} ", column);
}
Console.WriteLine();
}
Primes[N, M] – Example

int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());
for (int number = n; number <= m; number++)
{
bool prime = true;
int divider = 2;
int maxDivider = Math.Sqrt(num);
while (divider <= maxDivider)
{
if (number % divider == 0)
{
prime = false;
break;
}
divider++;
}
if (prime)
{
Console.Write("{0} ", number);
}
}
Questions?

You might also like