SlideShare a Scribd company logo
An Introduction 
to C# 
Lecture 1 
Dr. Hakem Beitollahi 
Computer Engineering Department 
Soran University
Objectives of this lecture 
 In this chapter you will learn: 
 To write simple C# applications. 
 To use input and output statements. 
 C#’s primitive types. 
 Basic memory concepts. 
 To use arithmetic operators. 
 The precedence of arithmetic operators. 
 To write decision-making statements. 
 To use relational and equality operators. 
An introduction to C#— 2
First program in C# 
An introduction to C#— 3
First C# program: printing a line 
Single-line comments. 
Left brace { begins function 
body. 
Predefined namespace (System)– part of .NET FCL 
User defined namespace 
User defined class 
A blank line 
Function Main returns 
nothing (void) and is static 
Function Main appears exactly once in every C# program.. 
Corresponding right brace } 
ends function body. 
Statements end with a 
semicolon ;. 
Console 
An introduction to C#— 4
Elements of a C# Program
Anatomy of the first program (I) 
// First program in C#. 
 Comments start with: // 
 Comments ignored during program execution 
 Document and describe code 
 Provides code readability 
 Traditional comments: /* ... */ 
/* This is a traditional 
comment. It can be 
split over many lines */ 
An introduction to C#— 6
Good Programming Practice Tip (1) 
 Every program should begin with a 
comment that explains the purpose of the 
program, the author and the date and time 
the program 
Chapter 3: An introduction to C# — 7
using Directive 
 Permits use of classes found in specific 
namespaces without having to qualify them 
 Framework class library 
 Over 2,000 classes included 
 Syntax 
 using namespaceIdentifier; 
An introduction to C#— 8
namespace 
 One of the great strengths of C# is that C# programmers 
can use the rich set of namespaces provided by the 
.NET 
 These namespaces contain code that programmers can 
reuse 
 framework.Groups semantically related types under a 
single umbrella 
 System: most important and frequently used namespace 
 An example of one of the features in namespace System is 
Console 
 We discuss many namespaces and their features 
throughout the course. 
An introduction to C#— 9
Blank line 
 Use blank lines and space characters 
throughout a program to make the 
program easier to read. 
 Collectively, blank lines, space characters, 
newline characters and tab characters are 
known as whitespace 
 The compiler ignores 
 blank lines, tabs and extra spaces that 
separate language elements. 
An introduction to C#— 10
 Our first class 
 C# programs consist of pieces called classes, which are 
logical groupings of members (e.g., methods) that 
simplify program organization. 
 These methods perform tasks and return information 
when the tasks are completed. 
 A C# program consists of classes and methods created 
by the programmer and of preexisting classes found in 
the Framework Class Library. 
 Every program in C# consists of at least one class 
definition that the programmer defines. 
 The class keyword begins a class definition in C# and is 
followed immediately by the class name (program) 
An introduction to C#— 11
Identifiers names 
 By convention, each word in a class name begins with an uppercase 
first letter and has an uppercase letter for each word in the class 
name: SampleClassName 
 Identifiers is a series of characters consisting of letters, digits, 
underscores ( _ ) and “at” symbols (@). 
 Identifiers cannot begin with a digit and cannot contain spaces. 
 The “at” character (@) can be used only as the first character in an 
identifier 
 Examples of valid identifiers: 
 Welcome1, _value, m_inputField1, button7, @value 
 Examples of invalid identifiers 
 5welcome, input field, val@, in$put 
 C# is case sensitive 
An introduction to C#— 12
Common Programming Error (1) 
C# is case sensitive. Not using the proper 
case for an identifier, e.g.,writing Total 
when the identifier is total, is a compiler 
error. 
An introduction to C#— 13
Good Programming Practice Tip (2) 
 Always begin a class name with an 
uppercase first letter. This practice makes 
class names easier to identify. 
An introduction to C#— 14
Braces { } 
 The left brace ({) begins the body of the 
class definition. 
 The corresponding right brace (}) ends the 
class definition. 
An introduction to C# — 15
Common Programming Error Tip (2) 
 If braces do not occur in matching pairs, a 
syntax error occurs. 
An introduction to C#— 16
Good Programming Practice Tip (3) 
 When typing an opening left brace ({) in a 
program, immediately type the closing 
right brace (}) then reposition the cursor 
between the braces to begin typing the 
body. 
An introduction to C#— 17
Good Programming Practice Tip (4) 
 Indent the entire body of each class definition 
one “level” of indentation between the left brace 
({) and the right brace (}) that delimit the class 
body. This emphasizes the structure of the class 
definition and helps make the class definition 
easier to read. 
An introduction to C#— 18
static void Main(string[] args) 
 present in all C# console and Windows applications. 
 These applications begin executing at Main, which is 
known as the entry point of the program. 
 The parentheses after Main indicate that Main is a 
program building block, called a method. 
 C# class definitions normally contain one or more 
methods and C# applications contain one or more 
classes. 
 For a C# console or Windows application, exactly one of 
those methods must be called Main 
 M in Main must be uppercase 
Administrative — 19
The Console 
 The Console class enables programs to output 
information to the computer’s standard output. 
 It provides methods to display strings and other types 
of information in the Windows command prompt. 
 Method Console.WriteLine displays (or prints) a line 
of text in the console window. 
 When Console.WriteLine completes its task, it 
positions the output cursor at the beginning of the next 
line in the console window. 
 Statement: The entire line, including Console.WriteLine, 
its argument in the parentheses ("Welcome to C# 
Programming!") and the semicolon (;) 
 Every statement must end with a semicolon. 
Chapter 3: An introduction to C#— 20
Common Programming Error Tip (3) 
 Omitting the semicolon at the end of a 
statement is a syntax error. 
 When the compiler reports a syntax error, 
the error might not be on the line indicated 
by the error message. First, check the line 
where the error was reported. If that line 
does not contain syntax errors, check the 
lines that precede the one reported. 
Chapter 3: An introduction to C#— 21
Administrative — 22 
// Fig. 3.4: Welcome2.cs 
// Printing a line with multiple statements. 
using System; 
class Welcome2 
{ 
static void Main( string[] args ) 
{ 
Console.Write( "Welcome to " ); 
Console.WriteLine( "C# Programming!" ); 
} 
} 
Console.Write keeps the curse in the last position
Modifying the first program 
(print same contents using different code) 
An introduction to C#— 23
// Fig. 3.5: Welcome3.cs 
// Printing multiple lines with a single statement. 
using System; 
class Welcome3 
{ 
static void Main( string[] args ) 
{ 
Console.WriteLine( "WelcomentonC#nProgramming!" ); 
} 
} 
Notice how a new line is output for 
each n escape sequence. 
An introduction to C#— 24
Slash Operator (I) 
An introduction to C#— 25
Slash Operator (II) 
Code Meaning 
b Backspace 
n Newline 
r Carriage return 
t Horizontal tab 
v Vertical tab 
” Double quote 
 backslash 
a Beep 
26/27
The Same Program in Windows Form Style 
An introduction to C#— 27
// Fig. 3.7: Welcome4.cs 
// Printing multiple lines in a dialog Box. 
using System; 
using System.Windows.Forms; 
class Welcome4 
{ 
static void Main( string[] args ) 
{ 
Class MessageBox 
is located in assembly 
System.Windows.Forms 
MessageBox.Show("WelcomentonC#nprogramming!"); 
} 
} 
An introduction to C#— 28
Common Programming Error Tip (4) 
 Including a namespace with the using 
directive, but not adding a reference to 
the proper assembly, results in a compiler 
error. 
An introduction to C#— 29
Add a reference to your program (I) 
 To begin, make sure you have an application 
open. Select the Add Reference… option from 
the Project menu, or right click the 
References folder in the Solution Explorer 
and select Add Reference… from the popup 
menu that appears. This opens the Add 
Reference dialog. Double click 
System.Windows.Forms.dll to add this file to 
the Selected Components list at the bottom of 
the dialog, then click OK. 
 See next slide 
An introduction to C#— 30
Add a reference to your program (II) 
An introduction to C#— 31
GUI EXample 
An introduction to C#— 32
Another Simple Program: Adding Integers 
An introduction to C#— 33
Addition Proggram 
// Fig. 3.11: Addition.cs 
// An addition program. 
using System; 
class Addition 
{ 
static void Main( string[] args ) 
{ 
string firstNumber, // first string entered by user 
secondNumber; // second string entered by user 
int number1, // first number to add 
number2, // second number to add 
sum; // sum of number1 and number2 
// prompt for and read first number from user as string 
Console.Write("Please enter the first integer: "); 
firstNumber = Console.ReadLine(); 
// read second number from user as string 
Console.Write("nPlease enter the second integer: "); 
secondNumber = Console.ReadLine(); 
// convert numbers from type string to type int 
number1 = Int32.Parse( firstNumber ); 
number2 = Int32.Parse( secondNumber ); 
// add numbers 
sum = number1 + number2; 
// display results 
Console.WriteLine( "nThe sum is {0}.", sum ); 
} // end method Main 
} //end class Addition 
Define two string variables to enter 
numbers 
Define three integer variables 
prompt for first number from user as 
string 
Read first number from user as string 
usinf ReadLine method 
convert numbers from type string to 
type int using Int32 class and Parse 
method 
Add numbers 
Display result in the screen 
An introduction to C#— 34
Variables 
 A variable is a location in the computer’s memory where 
a value can be stored for use by a program. 
 All variables must be declared with a name and a data 
type before they can be used in a program. 
 firstNumber and secondNumber are data of type string, 
which means that these variables store strings of 
characters. 
 Primitive data types: string, int, double and char 
 int holds integer values (whole numbers): i.e., 0, -4, 97 
 Types float and double can hold decimal numbers 
 Type char can hold a single character: i.e., x, $, n, 7 
 A variable name can be any valid identifier 
An introduction to C#— 35
Good Programming Practice Tip (5) 
 Choosing meaningful variable names helps a program to 
be “self-documenting” (i.e., easier to understand simply 
by reading it, rather than having to read manuals or use 
excessive comments). 
An introduction to C#— 36
Good Programming Practice Tip (6) 
 By convention, variable-name identifiers 
begin with a lowercase letter. As with class 
names, every word in the name after the 
first word should begin with a capital letter. 
For example, identifier firstNumber has a 
capital N in its second word, Number. 
An introduction to C#— 37
Good Programming Practice Tip (7) 
 Some programmers prefer to declare each 
variable on a separate line. This format 
allows for easy insertion of a comment that 
describes each variable. 
An introduction to C#— 38
Prompt 
Console.Write("Please enter the first integer: "); 
firstNumber = Console.ReadLine(); 
 prompt the user to input an integer and read from the 
user a string representing the first of the two integers 
that the program will add. 
 It is called a prompt, because it directs the user to take a 
specific action. 
 Method ReadLine causes the program to pause and wait 
for user input. 
 The user inputs characters from the keyboard, then 
presses the Enter key to return the string to the program. 
An introduction to C#— 39
Convert string to int 
// convert numbers from type string to type int 
number1 = Int32.Parse( firstNumber ); 
number2 = Int32.Parse( secondNumber ); 
 Method Int32.Parse converts its string 
argument to an integer. 
 Class Int32 is part of the System 
namespace. 
 assign the integer that Int32.Parse 
returns to variable number1. 
 The = operator is a binary operator 
An introduction to C#— 40
Good Programming Practice Tip (7) 
Place spaces on either side of a binary 
operator. This makes the operator stand 
out and makes the program more 
readable. 
An introduction to C#— 41
Sum 
// add numbers 
sum = number1 + number2; 
 calculates the sum of the variables 
number1 and number2 and assigns the 
result to variable sum by using the 
assignment operator =. 
An introduction to C#— 42
Display results (I) 
// display results 
Console.WriteLine( "nThe sum is {0}.", sum ); 
 It displays the result of the addition 
 we want to output the value in a variable 
using method WriteLine 
 use {0} to indicate a placeholder for a 
variable’s value. 
 Suppose sum =117, the resulting string 
will be “The sum is 117.” 
An introduction to C#— 43
Display results (II) 
Console.WriteLine("The numbers entered are {0} and {1}", number1, number2); 
 the value of number1 would replace {0} (because 
it is the first variable) and the value of number2 
would replace {1} (because it is the second 
variable). 
 The resulting string would be "The numbers 
entered are 45 and 72". 
 More formats can be used ({2}, {3} etc.) if there 
are more variables to display in the string. 
An introduction to C#— 44
Good Programming Practice Tip (8) 
 Place a space after each comma in a 
method’s argument list to make programs 
more readable. 
An introduction to C#— 45
Good Programming Practice Tip (9) 
 Follow the closing right brace (}) of the 
body of a method or class definition 
with a singleline comment. This comment 
should indicate the method or class that 
the right brace terminates. 
An introduction to C#— 46
Memory Concepts 
An introduction to C#— 47
Memory Concepts 
Number 1: 45 
Number 2: 72 
Sum: 117 
MMememoroyr ylo lcoactaiotinosn sa fateftre sr tcoarilncgu lavatinluge sa nfodr sntourminbge trh1e a snudm n uomf nbuemr2b.er1 and 
number2. 
Memory location showing the name and value of variable number1. 
An introduction to C#— 48
Arithmetic 
An introduction to C#— 49
Arithmetic Operations (I) 
An introduction to C#— 50
Arithmetic Operations (II) 
 Be careful! 
 5 / 2 yields an integer 2 
 5.0 / 2 yields a double value 2.5 
 Remainder can be very useful 
 Even numbers % 2 = 0 
 Today is Saturday and you and your friends are 
going to meet in 10 days. What day is in 10 days? 
Saturday is the 6th day in a week 
A week has 7 days 
After 10 days 
The 2nd day in a week is Tuesday 
(6 + 10) % 7 is 2 
An introduction to C#— 51
Arithmetic (III) 
 Operators have precedence 
 Some arithmetic operators act before others 
(i.e., multiplication before addition) 
 Use parenthesis when needed 
 Example: Find the average of three variables 
a, b and c 
 Do not use: a + b + c / 3 
 Use: ( a + b + c ) / 3 
An introduction to C#— 52
Arithmetic (IV) 
An introduction to C#— 53
 Operators have precedence 
1. Parentheses () 
2. *, /, % 
3. +,- 
4. … 
3 + 4 * 4 + 5 * (4 + 3) – 1 
3 + 4 * 4 + 5 * 7 – 1 
3 + 16 + 5 * 7 – 1 
3 + 16 + 35 – 1 
19 + 35 – 1 
54 – 1 
53 
in side parenthesis first 
multiplication 
multiplication 
addition 
addition 
subtraction 
An introduction to C#— 54 
Arithmetic (V)
Algebra: z = pr%q + w/x – y 
C#: z = p * r % q + w / x - y; 
1 
2 
3 
4 
5 
6 
An introduction to C#— 55 
Arithmetic (VI)
 Test yourself 
 y = a * x * x + b * x + c; 
 Y = a+b/(a%5)-a%a*3; (a= 7, b = 3) 
An introduction to C#— 56
Decision Making 
An introduction to C#— 57
Decision Making: Equality and Relational 
Operators (I) 
 Condition 
 Expression can be either true or false 
 if statement 
 Simple version in this section, more detail later 
 If a condition is true, then the body of the if 
statement executed 
 Control always resumes after the if statement 
 Conditions in if statements can be formed 
using equality or relational operators (next slide) 
An introduction to C#— 58
Decision Making: Equality and Relational 
Operators (II) 
An introduction to C#— 59
Common Programming Error Tip (5) 
It is a syntax error if the operators ==, !=, >= 
and<= contain spaces between their 
symbols (as in = =, ! =, > =, < =). 
An introduction to C#— 60
Common Programming Error Tip (6) 
 Reversing the operators !=, >= and <= (as 
in =!, => and =<) is a syntax error. 
An introduction to C#— 61
Common Programming Error Tip (7) 
 Confusing the equality operator == with 
the assignment operator = is a logic 
error. The equality operator should be 
read “is equal to,” and the assignment 
operator should be read “gets” or “gets the 
value of.” Some people prefer to read the 
equality operator as “double equals” or 
“equals equals.” 
An introduction to C#— 62
// Fig. 3.19: Comparison.cs 
// Using if statements, relational operators and equality operators. 
using System; 
class Comparison 
{ 
static void Main( string[] args ) 
{ 
int number1, // first number to compare 
number2; // second number to compare 
Directly get string 
and convert to int 
// read in first number from user 
Console.Write("Please enter first integer: "); 
number1 = Int32.Parse(Console.ReadLine()); 
// read in second number from user 
Console.Write("nPlease enter second integer: "); 
number2 = Int32.Parse(Console.ReadLine()); 
if (number1 == number2) 
Console.WriteLine(number1 + " == " + number2); 
if (number1 != number2) 
Console.WriteLine(number1 + " != " + number2); 
if (number1 < number2) 
Console.WriteLine(number1 + " < " + number2); 
if (number1 > number2) 
Console.WriteLine(number1 + " > " + number2); 
if (number1 <= number2) 
Console.WriteLine(number1 + " <= " + number2); 
if ( number1 >= number2 ) 
If condition is true (i.e., 
values are equal), execute this 
statement. 
Console.WriteLine( number1 + " >= " + number2 ); 
}// end method Main 
} // end class Comparison 
if structure compares values 
of num1 and num2 to test for 
equality. if structure compares values 
If condition is true (i.e., 
values are not equal), execute 
this statement. 
of num1 and num2 to test for 
inequality. 
An introduction to C#— 63
Console.WriteLine(number1 + " == " + number2); 
 This expression uses the operator + to 
“add” (or combine) numbers and strings. 
 C# has a version of the + operator used 
for string concatenation. 
 Concatenation is the process that enables 
a string and a value of another data type 
(including another string) to be combined 
to form a new string. 
An introduction to C#— 64
Common Programming Error Tip (8) 
 Confusing the + operator used for string 
concatenation with the + operator used for 
addition can lead to strange results 
 Assume y = 5; 
 The expression "y + 2 = " + y + 2 results in 
the string "y + 2 = 52“ and not "y + 2 = 7". 
 The expression "y + 2 = " + (y + 2) results 
in "y + 2 = 7“ 
An introduction to C#— 65
Common Programming Error Tip (9) 
 Replacing operator == in the condition 
of an if structure, such as if ( x == 1 ), 
with operator =, as in if ( x = 1 ), is a 
logic error. 
if (number1 = number2) 
Console.WriteLine(number1 + " == " + number2); 
An introduction to C#— 66
Common Programming Error Tip (10) 
 Forgetting the left and right parentheses 
for the condition in an if structure is a 
syntax error. The parentheses are 
required. 
if number1 == number2 
Console.WriteLine(number1 + " == " + number2); 
An introduction to C#— 67 
( )
Common Programming Error Tip (11) 
 There is no semicolon (;) at the end of the 
first line of each if structure. It is Syntax 
error. If takes no action. 
 Example: 
if (number1 == number2); 
Console.WriteLine(number1 + " == " + number2); 
An introduction to C#— 68
Good Programming Practice Tip (10) 
 Place only one statement per line in a 
program. This enhances program 
readability. 
An introduction to C#— 69
Good Programming Practice Tip (11) 
 A lengthy statement may be spread over several lines. 
 In case of splitting, choose breaking points that make 
sense, 
 after a comma in a comma separated list 
 after an operator in a lengthy expression. 
 Indent all subsequent lines with one level of indentation. 
 Example: 
int number1, // first number to add 
number2, // second number to add 
sum; // sum of number1 and number2 
An introduction to C#— 70
Good Programming Practice Tip (12) 
 Confirm that the operators in the expression are 
performed in the expected order. 
 If you are uncertain about the order of evaluation 
in a complex expression, use parentheses to 
force the order 
 assignment (=), associate from right to left rather 
than from left to right. 
 Example 
y = a * x * x + b * x + c; y = (a * x * x) + (b * x) + c; 
y = x; it means that x is assigned into y 
An introduction to C#— 71
HomeWork 
 First Homework 
 Write a program in C# that print your name 
with stars (*) in the screen 
* * 
* * 
* * * * 
* * 
* * 
* * * * 
* * 
* * * * 
* * 
* * 
* * 
* * 
* 
* * 
* * 
* * * * * 
* 
* * * * * 
* 
* * * * * 
Deadline: Next week 
* * 
* * * * 
* * * * 
* * * * 
* * * 
An introduction to C#— 72

More Related Content

PPTX
introduction to c #
PPT
C# basics
PPTX
Function C programming
PPTX
Strings in c++
PPTX
C# Tutorial
PPT
History of c++
PPT
PPT
Basic concept of OOP's
introduction to c #
C# basics
Function C programming
Strings in c++
C# Tutorial
History of c++
Basic concept of OOP's

What's hot (20)

PPTX
OOPS Basics With Example
PPS
Introduction to class in java
PPT
C#.NET
PPTX
classes and objects in C++
PPT
Abstract class
PPTX
Constructors in C++
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PPTX
Type conversion
PPTX
Std 12 computer chapter 6 object oriented concepts (part 1)
PPTX
Presentation on C++ Programming Language
PPTX
Java/Servlet/JSP/JDBC
PPTX
Functions in c
PPTX
Functions in python
PPTX
Programming Fundamentals lecture 1
PPTX
Basics of Object Oriented Programming in Python
PPTX
Python Functions
PDF
Object oriented approach in python programming
PPTX
Regular expressions in Python
PPTX
OOPS Basics With Example
Introduction to class in java
C#.NET
classes and objects in C++
Abstract class
Constructors in C++
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Type conversion
Std 12 computer chapter 6 object oriented concepts (part 1)
Presentation on C++ Programming Language
Java/Servlet/JSP/JDBC
Functions in c
Functions in python
Programming Fundamentals lecture 1
Basics of Object Oriented Programming in Python
Python Functions
Object oriented approach in python programming
Regular expressions in Python
Ad

Viewers also liked (20)

PPTX
FMS Spring Appeal 2014
DOCX
Generator dc
PDF
Slide11 icc2015
PDF
Incident manager - Apps for Good 2014 Entry
PPTX
Leadership development model npm
PPT
Beav ex interview questions and answers
PPTX
U.S. Department of Labor - OFFCP Contracts Compliance Officer Roles and Respo...
PDF
Tagmax_ebooklet
PDF
The 7 greatest cg aliens
DOCX
Anti inflammatory agents
PDF
Untitled Presentation
PPTX
Pengukuran aliran b.(variable area)
PDF
The definitive-guide-to LinkedIn
PPT
Reversting system
PPT
Administrative
PDF
Gym registration - 2014 Apps for Good Entry
PPT
Cozen o'connor interview questions and answers
PPT
Thrust block
PPTX
Tequipalcatalogo
FMS Spring Appeal 2014
Generator dc
Slide11 icc2015
Incident manager - Apps for Good 2014 Entry
Leadership development model npm
Beav ex interview questions and answers
U.S. Department of Labor - OFFCP Contracts Compliance Officer Roles and Respo...
Tagmax_ebooklet
The 7 greatest cg aliens
Anti inflammatory agents
Untitled Presentation
Pengukuran aliran b.(variable area)
The definitive-guide-to LinkedIn
Reversting system
Administrative
Gym registration - 2014 Apps for Good Entry
Cozen o'connor interview questions and answers
Thrust block
Tequipalcatalogo
Ad

Similar to Lecture 1 (20)

PPT
Basics1
DOCX
Chapter 3(1)
DOCX
C programming languag for cse students
DOCX
C language tutorial
PDF
fundamental of c++ for students of b.tech iii rd year student
PPT
Intro to c++
PDF
The C++ Programming Language
PPT
C Introduction and bascis of high level programming
DOCX
1 CMPS 12M Introduction to Data Structures Lab La.docx
PPTX
Unit 1.1 - Introduction to C.pptx
PPTX
Cordovilla
PDF
Introduction of c language
PDF
Learn C# programming - Program Structure & Basic Syntax
PPTX
C# lecture 1: Introduction to Dot Net Framework
PPT
Csphtp1 03
PDF
C class basic programming 1 PPT mayanka (1).pdf
PDF
C programming notes
PPTX
A POWERPOINT PRESENTATION ABOUT INTRODUCTION TO C#
PPTX
Overview of c
PPTX
Basics Of C++.pptx
Basics1
Chapter 3(1)
C programming languag for cse students
C language tutorial
fundamental of c++ for students of b.tech iii rd year student
Intro to c++
The C++ Programming Language
C Introduction and bascis of high level programming
1 CMPS 12M Introduction to Data Structures Lab La.docx
Unit 1.1 - Introduction to C.pptx
Cordovilla
Introduction of c language
Learn C# programming - Program Structure & Basic Syntax
C# lecture 1: Introduction to Dot Net Framework
Csphtp1 03
C class basic programming 1 PPT mayanka (1).pdf
C programming notes
A POWERPOINT PRESENTATION ABOUT INTRODUCTION TO C#
Overview of c
Basics Of C++.pptx

More from Soran University (7)

PPT
Lecture 9
PPT
Lecture 7
PPT
Lecture 8
PPT
Lecture 5
PPT
Lecture 4
PPT
Lecture 3
PPT
Lecture 2
Lecture 9
Lecture 7
Lecture 8
Lecture 5
Lecture 4
Lecture 3
Lecture 2

Recently uploaded (20)

PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Geodesy 1.pptx...............................................
DOCX
573137875-Attendance-Management-System-original
PPTX
Lecture Notes Electrical Wiring System Components
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPT
Project quality management in manufacturing
PDF
Well-logging-methods_new................
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Sustainable Sites - Green Building Construction
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
OOP with Java - Java Introduction (Basics)
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Geodesy 1.pptx...............................................
573137875-Attendance-Management-System-original
Lecture Notes Electrical Wiring System Components
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Project quality management in manufacturing
Well-logging-methods_new................
bas. eng. economics group 4 presentation 1.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Mechanical Engineering MATERIALS Selection
Foundation to blockchain - A guide to Blockchain Tech
Sustainable Sites - Green Building Construction
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026

Lecture 1

  • 1. An Introduction to C# Lecture 1 Dr. Hakem Beitollahi Computer Engineering Department Soran University
  • 2. Objectives of this lecture  In this chapter you will learn:  To write simple C# applications.  To use input and output statements.  C#’s primitive types.  Basic memory concepts.  To use arithmetic operators.  The precedence of arithmetic operators.  To write decision-making statements.  To use relational and equality operators. An introduction to C#— 2
  • 3. First program in C# An introduction to C#— 3
  • 4. First C# program: printing a line Single-line comments. Left brace { begins function body. Predefined namespace (System)– part of .NET FCL User defined namespace User defined class A blank line Function Main returns nothing (void) and is static Function Main appears exactly once in every C# program.. Corresponding right brace } ends function body. Statements end with a semicolon ;. Console An introduction to C#— 4
  • 5. Elements of a C# Program
  • 6. Anatomy of the first program (I) // First program in C#.  Comments start with: //  Comments ignored during program execution  Document and describe code  Provides code readability  Traditional comments: /* ... */ /* This is a traditional comment. It can be split over many lines */ An introduction to C#— 6
  • 7. Good Programming Practice Tip (1)  Every program should begin with a comment that explains the purpose of the program, the author and the date and time the program Chapter 3: An introduction to C# — 7
  • 8. using Directive  Permits use of classes found in specific namespaces without having to qualify them  Framework class library  Over 2,000 classes included  Syntax  using namespaceIdentifier; An introduction to C#— 8
  • 9. namespace  One of the great strengths of C# is that C# programmers can use the rich set of namespaces provided by the .NET  These namespaces contain code that programmers can reuse  framework.Groups semantically related types under a single umbrella  System: most important and frequently used namespace  An example of one of the features in namespace System is Console  We discuss many namespaces and their features throughout the course. An introduction to C#— 9
  • 10. Blank line  Use blank lines and space characters throughout a program to make the program easier to read.  Collectively, blank lines, space characters, newline characters and tab characters are known as whitespace  The compiler ignores  blank lines, tabs and extra spaces that separate language elements. An introduction to C#— 10
  • 11.  Our first class  C# programs consist of pieces called classes, which are logical groupings of members (e.g., methods) that simplify program organization.  These methods perform tasks and return information when the tasks are completed.  A C# program consists of classes and methods created by the programmer and of preexisting classes found in the Framework Class Library.  Every program in C# consists of at least one class definition that the programmer defines.  The class keyword begins a class definition in C# and is followed immediately by the class name (program) An introduction to C#— 11
  • 12. Identifiers names  By convention, each word in a class name begins with an uppercase first letter and has an uppercase letter for each word in the class name: SampleClassName  Identifiers is a series of characters consisting of letters, digits, underscores ( _ ) and “at” symbols (@).  Identifiers cannot begin with a digit and cannot contain spaces.  The “at” character (@) can be used only as the first character in an identifier  Examples of valid identifiers:  Welcome1, _value, m_inputField1, button7, @value  Examples of invalid identifiers  5welcome, input field, val@, in$put  C# is case sensitive An introduction to C#— 12
  • 13. Common Programming Error (1) C# is case sensitive. Not using the proper case for an identifier, e.g.,writing Total when the identifier is total, is a compiler error. An introduction to C#— 13
  • 14. Good Programming Practice Tip (2)  Always begin a class name with an uppercase first letter. This practice makes class names easier to identify. An introduction to C#— 14
  • 15. Braces { }  The left brace ({) begins the body of the class definition.  The corresponding right brace (}) ends the class definition. An introduction to C# — 15
  • 16. Common Programming Error Tip (2)  If braces do not occur in matching pairs, a syntax error occurs. An introduction to C#— 16
  • 17. Good Programming Practice Tip (3)  When typing an opening left brace ({) in a program, immediately type the closing right brace (}) then reposition the cursor between the braces to begin typing the body. An introduction to C#— 17
  • 18. Good Programming Practice Tip (4)  Indent the entire body of each class definition one “level” of indentation between the left brace ({) and the right brace (}) that delimit the class body. This emphasizes the structure of the class definition and helps make the class definition easier to read. An introduction to C#— 18
  • 19. static void Main(string[] args)  present in all C# console and Windows applications.  These applications begin executing at Main, which is known as the entry point of the program.  The parentheses after Main indicate that Main is a program building block, called a method.  C# class definitions normally contain one or more methods and C# applications contain one or more classes.  For a C# console or Windows application, exactly one of those methods must be called Main  M in Main must be uppercase Administrative — 19
  • 20. The Console  The Console class enables programs to output information to the computer’s standard output.  It provides methods to display strings and other types of information in the Windows command prompt.  Method Console.WriteLine displays (or prints) a line of text in the console window.  When Console.WriteLine completes its task, it positions the output cursor at the beginning of the next line in the console window.  Statement: The entire line, including Console.WriteLine, its argument in the parentheses ("Welcome to C# Programming!") and the semicolon (;)  Every statement must end with a semicolon. Chapter 3: An introduction to C#— 20
  • 21. Common Programming Error Tip (3)  Omitting the semicolon at the end of a statement is a syntax error.  When the compiler reports a syntax error, the error might not be on the line indicated by the error message. First, check the line where the error was reported. If that line does not contain syntax errors, check the lines that precede the one reported. Chapter 3: An introduction to C#— 21
  • 22. Administrative — 22 // Fig. 3.4: Welcome2.cs // Printing a line with multiple statements. using System; class Welcome2 { static void Main( string[] args ) { Console.Write( "Welcome to " ); Console.WriteLine( "C# Programming!" ); } } Console.Write keeps the curse in the last position
  • 23. Modifying the first program (print same contents using different code) An introduction to C#— 23
  • 24. // Fig. 3.5: Welcome3.cs // Printing multiple lines with a single statement. using System; class Welcome3 { static void Main( string[] args ) { Console.WriteLine( "WelcomentonC#nProgramming!" ); } } Notice how a new line is output for each n escape sequence. An introduction to C#— 24
  • 25. Slash Operator (I) An introduction to C#— 25
  • 26. Slash Operator (II) Code Meaning b Backspace n Newline r Carriage return t Horizontal tab v Vertical tab ” Double quote backslash a Beep 26/27
  • 27. The Same Program in Windows Form Style An introduction to C#— 27
  • 28. // Fig. 3.7: Welcome4.cs // Printing multiple lines in a dialog Box. using System; using System.Windows.Forms; class Welcome4 { static void Main( string[] args ) { Class MessageBox is located in assembly System.Windows.Forms MessageBox.Show("WelcomentonC#nprogramming!"); } } An introduction to C#— 28
  • 29. Common Programming Error Tip (4)  Including a namespace with the using directive, but not adding a reference to the proper assembly, results in a compiler error. An introduction to C#— 29
  • 30. Add a reference to your program (I)  To begin, make sure you have an application open. Select the Add Reference… option from the Project menu, or right click the References folder in the Solution Explorer and select Add Reference… from the popup menu that appears. This opens the Add Reference dialog. Double click System.Windows.Forms.dll to add this file to the Selected Components list at the bottom of the dialog, then click OK.  See next slide An introduction to C#— 30
  • 31. Add a reference to your program (II) An introduction to C#— 31
  • 32. GUI EXample An introduction to C#— 32
  • 33. Another Simple Program: Adding Integers An introduction to C#— 33
  • 34. Addition Proggram // Fig. 3.11: Addition.cs // An addition program. using System; class Addition { static void Main( string[] args ) { string firstNumber, // first string entered by user secondNumber; // second string entered by user int number1, // first number to add number2, // second number to add sum; // sum of number1 and number2 // prompt for and read first number from user as string Console.Write("Please enter the first integer: "); firstNumber = Console.ReadLine(); // read second number from user as string Console.Write("nPlease enter the second integer: "); secondNumber = Console.ReadLine(); // convert numbers from type string to type int number1 = Int32.Parse( firstNumber ); number2 = Int32.Parse( secondNumber ); // add numbers sum = number1 + number2; // display results Console.WriteLine( "nThe sum is {0}.", sum ); } // end method Main } //end class Addition Define two string variables to enter numbers Define three integer variables prompt for first number from user as string Read first number from user as string usinf ReadLine method convert numbers from type string to type int using Int32 class and Parse method Add numbers Display result in the screen An introduction to C#— 34
  • 35. Variables  A variable is a location in the computer’s memory where a value can be stored for use by a program.  All variables must be declared with a name and a data type before they can be used in a program.  firstNumber and secondNumber are data of type string, which means that these variables store strings of characters.  Primitive data types: string, int, double and char  int holds integer values (whole numbers): i.e., 0, -4, 97  Types float and double can hold decimal numbers  Type char can hold a single character: i.e., x, $, n, 7  A variable name can be any valid identifier An introduction to C#— 35
  • 36. Good Programming Practice Tip (5)  Choosing meaningful variable names helps a program to be “self-documenting” (i.e., easier to understand simply by reading it, rather than having to read manuals or use excessive comments). An introduction to C#— 36
  • 37. Good Programming Practice Tip (6)  By convention, variable-name identifiers begin with a lowercase letter. As with class names, every word in the name after the first word should begin with a capital letter. For example, identifier firstNumber has a capital N in its second word, Number. An introduction to C#— 37
  • 38. Good Programming Practice Tip (7)  Some programmers prefer to declare each variable on a separate line. This format allows for easy insertion of a comment that describes each variable. An introduction to C#— 38
  • 39. Prompt Console.Write("Please enter the first integer: "); firstNumber = Console.ReadLine();  prompt the user to input an integer and read from the user a string representing the first of the two integers that the program will add.  It is called a prompt, because it directs the user to take a specific action.  Method ReadLine causes the program to pause and wait for user input.  The user inputs characters from the keyboard, then presses the Enter key to return the string to the program. An introduction to C#— 39
  • 40. Convert string to int // convert numbers from type string to type int number1 = Int32.Parse( firstNumber ); number2 = Int32.Parse( secondNumber );  Method Int32.Parse converts its string argument to an integer.  Class Int32 is part of the System namespace.  assign the integer that Int32.Parse returns to variable number1.  The = operator is a binary operator An introduction to C#— 40
  • 41. Good Programming Practice Tip (7) Place spaces on either side of a binary operator. This makes the operator stand out and makes the program more readable. An introduction to C#— 41
  • 42. Sum // add numbers sum = number1 + number2;  calculates the sum of the variables number1 and number2 and assigns the result to variable sum by using the assignment operator =. An introduction to C#— 42
  • 43. Display results (I) // display results Console.WriteLine( "nThe sum is {0}.", sum );  It displays the result of the addition  we want to output the value in a variable using method WriteLine  use {0} to indicate a placeholder for a variable’s value.  Suppose sum =117, the resulting string will be “The sum is 117.” An introduction to C#— 43
  • 44. Display results (II) Console.WriteLine("The numbers entered are {0} and {1}", number1, number2);  the value of number1 would replace {0} (because it is the first variable) and the value of number2 would replace {1} (because it is the second variable).  The resulting string would be "The numbers entered are 45 and 72".  More formats can be used ({2}, {3} etc.) if there are more variables to display in the string. An introduction to C#— 44
  • 45. Good Programming Practice Tip (8)  Place a space after each comma in a method’s argument list to make programs more readable. An introduction to C#— 45
  • 46. Good Programming Practice Tip (9)  Follow the closing right brace (}) of the body of a method or class definition with a singleline comment. This comment should indicate the method or class that the right brace terminates. An introduction to C#— 46
  • 47. Memory Concepts An introduction to C#— 47
  • 48. Memory Concepts Number 1: 45 Number 2: 72 Sum: 117 MMememoroyr ylo lcoactaiotinosn sa fateftre sr tcoarilncgu lavatinluge sa nfodr sntourminbge trh1e a snudm n uomf nbuemr2b.er1 and number2. Memory location showing the name and value of variable number1. An introduction to C#— 48
  • 50. Arithmetic Operations (I) An introduction to C#— 50
  • 51. Arithmetic Operations (II)  Be careful!  5 / 2 yields an integer 2  5.0 / 2 yields a double value 2.5  Remainder can be very useful  Even numbers % 2 = 0  Today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? Saturday is the 6th day in a week A week has 7 days After 10 days The 2nd day in a week is Tuesday (6 + 10) % 7 is 2 An introduction to C#— 51
  • 52. Arithmetic (III)  Operators have precedence  Some arithmetic operators act before others (i.e., multiplication before addition)  Use parenthesis when needed  Example: Find the average of three variables a, b and c  Do not use: a + b + c / 3  Use: ( a + b + c ) / 3 An introduction to C#— 52
  • 53. Arithmetic (IV) An introduction to C#— 53
  • 54.  Operators have precedence 1. Parentheses () 2. *, /, % 3. +,- 4. … 3 + 4 * 4 + 5 * (4 + 3) – 1 3 + 4 * 4 + 5 * 7 – 1 3 + 16 + 5 * 7 – 1 3 + 16 + 35 – 1 19 + 35 – 1 54 – 1 53 in side parenthesis first multiplication multiplication addition addition subtraction An introduction to C#— 54 Arithmetic (V)
  • 55. Algebra: z = pr%q + w/x – y C#: z = p * r % q + w / x - y; 1 2 3 4 5 6 An introduction to C#— 55 Arithmetic (VI)
  • 56.  Test yourself  y = a * x * x + b * x + c;  Y = a+b/(a%5)-a%a*3; (a= 7, b = 3) An introduction to C#— 56
  • 57. Decision Making An introduction to C#— 57
  • 58. Decision Making: Equality and Relational Operators (I)  Condition  Expression can be either true or false  if statement  Simple version in this section, more detail later  If a condition is true, then the body of the if statement executed  Control always resumes after the if statement  Conditions in if statements can be formed using equality or relational operators (next slide) An introduction to C#— 58
  • 59. Decision Making: Equality and Relational Operators (II) An introduction to C#— 59
  • 60. Common Programming Error Tip (5) It is a syntax error if the operators ==, !=, >= and<= contain spaces between their symbols (as in = =, ! =, > =, < =). An introduction to C#— 60
  • 61. Common Programming Error Tip (6)  Reversing the operators !=, >= and <= (as in =!, => and =<) is a syntax error. An introduction to C#— 61
  • 62. Common Programming Error Tip (7)  Confusing the equality operator == with the assignment operator = is a logic error. The equality operator should be read “is equal to,” and the assignment operator should be read “gets” or “gets the value of.” Some people prefer to read the equality operator as “double equals” or “equals equals.” An introduction to C#— 62
  • 63. // Fig. 3.19: Comparison.cs // Using if statements, relational operators and equality operators. using System; class Comparison { static void Main( string[] args ) { int number1, // first number to compare number2; // second number to compare Directly get string and convert to int // read in first number from user Console.Write("Please enter first integer: "); number1 = Int32.Parse(Console.ReadLine()); // read in second number from user Console.Write("nPlease enter second integer: "); number2 = Int32.Parse(Console.ReadLine()); if (number1 == number2) Console.WriteLine(number1 + " == " + number2); if (number1 != number2) Console.WriteLine(number1 + " != " + number2); if (number1 < number2) Console.WriteLine(number1 + " < " + number2); if (number1 > number2) Console.WriteLine(number1 + " > " + number2); if (number1 <= number2) Console.WriteLine(number1 + " <= " + number2); if ( number1 >= number2 ) If condition is true (i.e., values are equal), execute this statement. Console.WriteLine( number1 + " >= " + number2 ); }// end method Main } // end class Comparison if structure compares values of num1 and num2 to test for equality. if structure compares values If condition is true (i.e., values are not equal), execute this statement. of num1 and num2 to test for inequality. An introduction to C#— 63
  • 64. Console.WriteLine(number1 + " == " + number2);  This expression uses the operator + to “add” (or combine) numbers and strings.  C# has a version of the + operator used for string concatenation.  Concatenation is the process that enables a string and a value of another data type (including another string) to be combined to form a new string. An introduction to C#— 64
  • 65. Common Programming Error Tip (8)  Confusing the + operator used for string concatenation with the + operator used for addition can lead to strange results  Assume y = 5;  The expression "y + 2 = " + y + 2 results in the string "y + 2 = 52“ and not "y + 2 = 7".  The expression "y + 2 = " + (y + 2) results in "y + 2 = 7“ An introduction to C#— 65
  • 66. Common Programming Error Tip (9)  Replacing operator == in the condition of an if structure, such as if ( x == 1 ), with operator =, as in if ( x = 1 ), is a logic error. if (number1 = number2) Console.WriteLine(number1 + " == " + number2); An introduction to C#— 66
  • 67. Common Programming Error Tip (10)  Forgetting the left and right parentheses for the condition in an if structure is a syntax error. The parentheses are required. if number1 == number2 Console.WriteLine(number1 + " == " + number2); An introduction to C#— 67 ( )
  • 68. Common Programming Error Tip (11)  There is no semicolon (;) at the end of the first line of each if structure. It is Syntax error. If takes no action.  Example: if (number1 == number2); Console.WriteLine(number1 + " == " + number2); An introduction to C#— 68
  • 69. Good Programming Practice Tip (10)  Place only one statement per line in a program. This enhances program readability. An introduction to C#— 69
  • 70. Good Programming Practice Tip (11)  A lengthy statement may be spread over several lines.  In case of splitting, choose breaking points that make sense,  after a comma in a comma separated list  after an operator in a lengthy expression.  Indent all subsequent lines with one level of indentation.  Example: int number1, // first number to add number2, // second number to add sum; // sum of number1 and number2 An introduction to C#— 70
  • 71. Good Programming Practice Tip (12)  Confirm that the operators in the expression are performed in the expected order.  If you are uncertain about the order of evaluation in a complex expression, use parentheses to force the order  assignment (=), associate from right to left rather than from left to right.  Example y = a * x * x + b * x + c; y = (a * x * x) + (b * x) + c; y = x; it means that x is assigned into y An introduction to C#— 71
  • 72. HomeWork  First Homework  Write a program in C# that print your name with stars (*) in the screen * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Deadline: Next week * * * * * * * * * * * * * * * * * An introduction to C#— 72