Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Windows Programming

Chapter two
Language Fundamentals in C#

1 Prepared by Tesfa K. 5/15/2022


Working with Variables and Data Types
 A variable is a memory location where a value is stored.
 For example, if you wanted to count the number of times a user
tries to log in to an application, you could use a variable to track
the number of attempts.
 Using the variable, your program can read or alter the value stored in
memory.
 Before you use a variable in your program, however, you must
declare it.
 A variable declaration reserves memory space for the variable
and may optionally specify an initial value.
 When you declare a variable, the compiler also needs to know
what kind of data will be stored at the memory location.

2 Prepared by Tesfa K. 5/15/2022


Declaring a Variable
 Syntax:
type variable_name = value;
type variable_names;
 Rules that must be followed while declaring variables :
 name : It must be a valid identifier.
 Variable names can contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well
as the character ‘_’.
 The name of the variables cannot be started with a digit.
 The name of the variable cannot be any C# keyword
 type : It defines the types of information which is to be stored into the
variable.
 value : It is the actual data which is to be stored in the variable.
 Example
string name = "John";

3 Prepared by Tesfa K. 5/15/2022


Declaring a variable with var keyword
 var is a keyword, it is used to declare an implicit type variable, that determine the
data type of a variable based on initial value.
 Syntax:

var variable_name = value;


1. static void Main(string[] args)
2. {
3. var a = 637;
4. var b = -9721087085262;
5. Console.WriteLine( " Type of 637 is="+a.GetType());
6. Console.WriteLine( " Type of -9721087085262 is= " +b.GetType());
7. }
Output:
 Type of 637 is= System.Int32

 Type of -9721087085262 is= System.Int64


4 Prepared by Tesfa K. 5/15/2022
Working with Variables and Data Types
 The variables in C#, are categorized into the
following types:
1. Value types
2. Reference types

5 Prepared by Tesfa K. 5/15/2022


Value Type
 Value type variables can be assigned a value directly.
 A value type variables holds a data value within its own memory space.

6 Prepared by Tesfa K. 5/15/2022


Reference type
 A reference type variable just holds a reference to a particular
memory location that may hold the required data.
 If any changes are made to the data then the other variable will
automatically inherit the new changed value
 If there are no values assigned to the reference type then by default
it contains a null value.
 Different reference type:
 Object type
 Dynamic type
 String
 Pointer

7 Prepared by Tesfa K. 5/15/2022


Object type
 Object type is a special type, which is the parent of all other types in the .NET
Framework.
 Every type in C# derives from the object type
 Declaring a variable with the keyword object, it can take values from any
other type.
 It is a reference type that points to the memory location of another data type
which stores the actual value.
 It is commonly used to declare variables when the actual data type can’t be
determined until runtime.
 Example
// Declare some variables
object container1 = 5;
object container2 = "Five";
// Print the results on the console
Console.WriteLine("The value of container1 is: " + container1);
Console.WriteLine("The value of container2 is: " + container2);
8 Prepared by Tesfa K. 5/15/2022
Object type…
 The values of different data types are treated as objects by using boxing and
unboxing.
 It is boxing when the value type is converted to object type and unboxing
when object type is converted to value type.
 Source Code: Program to implement Boxing and Unboxing in C#
1. using System;
2. class Demo
3. {
4. static void Main()
5. {
6. int val1 = 100;
7. object obj = val1; // This is Boxing
8. int val2 = (int)obj; // This is Unboxing
9. }
10. }

9 Prepared by Tesfa K. 5/15/2022


Dynamic type
 C# 4.0 (.NET 4.5) introduced a new type called dynamic that avoids
compile-time type checking.
 A dynamic type escapes type checking at compile-time; instead, it resolves
type at run time.
 A dynamic type variables are defined using the dynamic keyword.
Example: dynamic MyDynamicVar = 1;
 The compiler compiles dynamic types into object types in most cases.
 However, the actual type of a dynamic type variable would be resolved at
run-time.
 Example: dynamic Type at run-time
1. Dynamic MyDynamicVar = 1;
2. Console.WriteLine(MyDynamicVar.GetType());
3. Output: System.Int32

10 Prepared by Tesfa K. 5/15/2022


String type
 The string data type is used to store a sequence of
characters (text).
 String values must be surrounded by double quotes:
1. using System;
2. public class Demo
3. {
4. public static void Main()
5. {
6. string a = "Hello";
7. Console.WriteLine(a); // Displays Hello
8. }
9. }

11 Prepared by Tesfa K. 5/15/2022


Concatenation of Strings
 In C# the addition operation (+) used to concatenates two strings together
and returns as a new string.
 Example
string age = "twenty six";
string text = "He is " + age + " years old.";
Console.WriteLine(text);
 The result of this code execution is again a string:
 He is twenty six years old.
 be careful when concatenate string
string s = "Four: " + 2 + 2;
Console.WriteLine(s); // Four: 22
string s1 = "Four: " + (2 + 2);
Console.WriteLine(s1); // Four: 4

12 Prepared by Tesfa K. 5/15/2022


Pointer data type
 The pointer data types in C# store the address of another data type.
 They are used in an unsafe context i.e. an unsafe modifier is required in the program to use
pointers..
 The syntax of the pointer data type is as follows:
type* identifier;
 A program that demonstrates pointers is as follows:
1. using System;
2. namespace PointerDemo {
3. class Example {
4. static unsafe void Main(string[] args)
5. {
6. int val = 100;
7. int* ptr = &val;
8. Console.WriteLine("Data value is: {0} ", val);
9. Console.WriteLine("Address of the data value is: {0}", (int)ptr);
10. }}
11. }

13 Prepared by Tesfa K. 5/15/2022


Pointer data type…
 It is also possible to write like this to avoid the
whole unsafe

1. unsafe
2. {
3. int val = 100;
4. int* ptr = &val;
5. Console.WriteLine("Data is: {0} ", val);
6. Console.WriteLine("Address is: {0} ", (int)ptr);
7. }

14 Prepared by Tesfa K. 5/15/2022


Consol input/output
 The Console is a window of the operating system through
which users can interact with system programs of the
operating system or with other console applications.
 It is a tools for communication between programs and
users
 The interaction consists of text input from the standard
input (usually keyboard) or text display on the standard
output (usually on the computer screen).
 These actions are also known as input-output operations.

15 Prepared by Tesfa K. 5/15/2022


Consol input/output…
 When we run console application it automatically read the user
input from the standard input stream (Console.In) and print
information on the standard output stream (Console.Out)
 System.Console class has different properties and methods which
are used to read and display text on the console
 The most commonly used methods for text printing on the
console are:- Console.Write() and Console.WriteLine()
 They can print all the basic types (string, numeric and primitive
types).
 The difference between Write() and WriteLine() is that the Write()
method prints on the console but does nothing in addition while
the method WriteLine() print a new line after printing.
16 Prepared by Tesfa K. 5/15/2022
Consol input/output…
Example
1. // Print String
2. Console.WriteLine("Hello World");
3. // Print int
4. Console.WriteLine(5);
5. // Print double
6. Console.WriteLine(3.14159265358979);
 Out put
 Hello World
 5
 3.14159265358979

17 Prepared by Tesfa K. 5/15/2022


Consol input/output…
 In C# we can display formatted Output with Write() and WriteLine() method using
special formatting characters and list of values, which should be substituted in place of “the
format specifiers”.
 Here is the general form of Write() method with format specifier
public static void Write(string format, object arg0, object arg1, object arg2, object arg3, …);
Example
string name = "John";
int age = 18;
string town = "Seattle";
Console.Write( "{0} is {1} years old from {2}!\n", name, age, town);
 First argument is the format string. It contain index item in curly bracket symbol which is
an integer value indicating the position of the argument from the argument list.
 In this case {0} is a place holder for the first argument, {1} is place holder for second
argument, {2} place holder for the third argument.
 The result would be:-
John is 18 years old from Seattle!

18 Prepared by Tesfa K. 5/15/2022


Consol input/output…
 In cases if some of the arguments are not referenced
by any of the formatting items, those arguments are
simply ignored and do not play a role.
 Example:-
Console.Write( "{1} is {0} years old from {3}!", 18, "John", 0, "Seattle");
 However , when a formatting item refers an argument
that does not exist in the list of arguments, an
exception is thrown.

19 Prepared by Tesfa K. 5/15/2022


Consol input/output…
 The object that controls the standard input stream in C#, is Console.In.
 From the console we can read different data: ( text and other types after parsing the text)
 The class Console provides two methods Console.Read() and Console.ReadLine() for reading
data.
 The method Console.ReadLine() returns string entered by the user when the [Enter] key
is pressed.
1. class UsingReadLine
2. {
3. static void Main()
4. {
5. Console.Write("Please enter your first name: ");
6. string firstName = Console.ReadLine();
7. Console.Write("Please enter your last name: ");
8. string lastName = Console.ReadLine();
9. Console.WriteLine("Hello, {0} {1}!", firstName, lastName);
10. }
11. }

20 Prepared by Tesfa K. 5/15/2022


Consol input/output…
Reading through Console.Read()
 The method Read() reads only one character and not
the entire line.
 The method does not return directly the read character
but its code (i.e. int value)
 If we want to use the result as a character we must
convert it to a character using the method
Convert.ToChar() or you can cast the input integer.
 The character is read only when the [Enter] key is pressed.
 If you enter string and try to read with Console.Read()
method it reads the first character only.

21 Prepared by Tesfa K. 5/15/2022


Consol input/output…
 Reading numbers from the console in C# is not done directly.
 In order to read a number we should have to read the input as a string
(using ReadLine()) and then convert this string to a number.
 The operation of converting a string into another type is called parsing.
 All primitive types have methods for parsing.
 Example
Console.Write("a = ");
int a = int.Parse(Console.ReadLine());
 When parsing a string to a number using the method
Int32.Parse(string) or by Convert.ToInt32(string)
 Example
int value1=Convert.ToInt32(Console.ReadLine()); //take int type

22 Prepared by Tesfa K. 5/15/2022


Control Flows in C#
 Control flow - refers to the order in which the individual
statements or instructions of a program are executed.
 Like in any programming language, C# provides
statements that can change the sequence of program
execution.
 When the program is run, the statements are executed
from the top to bottom. One by one.
 This flow can be altered by conditional statements.
 Conditional statements is executed only if a specific
condition is met.

23 Prepared by Tesfa K. 5/15/2022


C# if statement
 The if statement has the following general form:
if (expression)
{
statement;
}
 The if keyword is used to check if an expression is true.
 If it is true, a statement is then executed.
 The statement can be a single statement or a compound
statement.
 A compound statement consists of multiple statements
enclosed by the block.
 A block is code enclosed by curly brackets.

24 Prepared by Tesfa K. 5/15/2022


C# if statement…
 Example:
1. using System;
2. var r = new Random();
3. int n = r.Next(-5, 5);
4. Console.WriteLine(n);
5. if (n > 0)
6. {
7. Console.WriteLine("The number is positive");
// only returns +vs values
8. }

25 Prepared by Tesfa K. 5/15/2022


C# else statement
 We can use the else keyword to create a simple branch.
 If the expression inside the square brackets following the if keyword evaluates
to false, the statement following the else keyword is automatically executed.
 Example:
1. using System;
2. var r = new Random();
3. int n = r.Next(-5, 5)
4. Console.WriteLine(n);
5. if (n > 0)
6. {
7. Console.WriteLine("The number is positive"); // returns +vs values
8. }
9. else
10. {
11. Console.WriteLine("The number is negative"); // returns -ve value
12. }
26 Prepared by Tesfa K. 5/15/2022
C# else if
 We can create multiple branches using the else if keyword.
 The else if keyword tests for another condition if and only if the previous condition was not met.
 Note that we can use multiple else if keywords in our tests.
 Example:
1. using System;
2. var r = new Random();
3. int n = r.Next(-5, 5);
4. Console.WriteLine(n);
5. if (n < 0)
6. {
7. Console.WriteLine("The n variable is negative");
8. }
9. else if (n == 0)
10. {
11. Console.WriteLine("The n variable is zero");
12. }
13. else
14. {
15. Console.WriteLine("The n variable is positive");
16. }

27 Prepared by Tesfa K. 5/15/2022


C# switch statement
 The switch statement is a selection of control flow statement.
 It allows the value of a variable or expression to control the flow of
program execution via a multi-way branch.
 It creates multiple branches in a simpler way than using the
combination of if/else if/else statements.
 The switch keyword is used to test a value from the variable or
the expression against a list of values.
 The list of values is presented with the case keyword.
 If the values match, the statement following the case is
executed.
 There is an optional default statement.
 It is executed if no other match is found.

28 Prepared by Tesfa K. 5/15/2022


C# switch statement Example
14. case DayOfWeek.Wednesday:
1. using System; 15. Console.WriteLine("dies Mercurii");
2. var dayOfWeek = DateTime.Now.DayOfWeek;
16. break;
3. switch (dayOfWeek) 17. case DayOfWeek.Thursday:
4. { 18. Console.WriteLine("dies Jovis");
5. case DayOfWeek.Sunday: 19. break;
6. Console.WriteLine("dies Solis"); 20. case DayOfWeek.Friday:
7. break; 21. Console.WriteLine("dies Veneris");
8. case DayOfWeek.Monday: 22. break;
9. Console.WriteLine("dies Lunae"); 23. case DayOfWeek.Saturday:
10. break; 24. Console.WriteLine("dies Saturni");
11. case DayOfWeek.Tuesday: 25. break;
12. Console.WriteLine("dies Martis"); 26. }
13. break; The example determines the
current day of week and prints its
Latin equivalent.

29 Prepared by Tesfa K. 5/15/2022


Enum in a Switch Statement
 An enum is a special "class" that represents a group of constants
 To create an enum, use the enum keyword (instead of class or interface), and separate the
enum items with a comma:
1. class Program {
2. enum Level { Low, Medium, High }
3. static void Main(string[] args)
4. {
5. Level myVar = Level.Medium;
6. Console.WriteLine(myVar);
7. }}
 Enum Values
 By default, the first item of an enum has the value 0. The second has the value 1, and so on.

 To get the integer value from an item, you must explicitly convert the item to an int:

30 Prepared by Tesfa K. 5/15/2022


Enum in a Switch Statement…
enum Months {
January, // 0
February, // 1
March, // 2
April, // 3
May, // 4
June, // 5
July // 6
}
static void Main(string[] args) {
int myNum = (int) Months.April;
Console.WriteLine(myNum);
}

31 Prepared by Tesfa K. 5/15/2022


Enum in a Switch Statement…
 Enums are often used in switch statements to check for corresponding values:
1. enum Level { Low, Medium, High }
2. static void Main(string[] args)
3. {
4. Level myVar = Level.Medium;
5. switch(myVar)
6. {
7. case Level.Low:
8. Console.WriteLine("Low level");
9. break;
10. case Level.Medium:
11. Console.WriteLine("Medium level");
12. break;
13. case Level.High:
14. Console.WriteLine("High level");
15. break;
16. }}

32 Prepared by Tesfa K. 5/15/2022


C# while Loop Statement
 The while statement is a control flow statement that allows code to
be executed repeatedly based on a given boolean condition.
 This is the general form of the while loop:
while (expression)
{
statement;
}
 The while keyword executes the statements inside the block enclosed
by the curly brackets.
 The statements are executed each time the expression is evaluated to
true.

33 Prepared by Tesfa K. 5/15/2022


C# while Loop Statement…
 Example:
1. using System;
2. int i = 0;
3. int sum = 0;
4. while (i < 10)
5. {
6. i++;
7. sum += i;
8. }
9. Console.WriteLine(sum);
 In the code example, we calculate the sum of values from a range of
numbers.
 The while loop has three parts. Initialization, testing and updating.
 Each execution of the statement is called a cycle.

34 Prepared by Tesfa K. 5/15/2022


Do-while loop statement
 It is possible to run the statement at least once, even if the condition is not met.
 For this, we can use the do while keywords.
 Example:
1. using System;
2. int sum = 0;
3. int count = 1;
4. do
5. {
6. sum = sum + count;
7. count++;
8. } while (count <= 10);
9. Console.WriteLine("The sum of the first 10 integer numbers={0}",sum);

 First the block is executed and then the truth expression is evaluated.
 In our case, the condition is not met and the do while statement terminates.

35 Prepared by Tesfa K. 5/15/2022


for loop statement
 When the number of cycles is know before the loop is initiated, we
can use the for statement.
 In this construct we declare a counter variable which is automatically
increased or decreased in value during each repetition of the loop.
 Simple for loop:
 A for loop has three phases: initialization, condition and code
block execution, and increamentation/ decreamentation.
1. using System;
2. for (int i=0; i<10; i++)
3. {
4. Console.WriteLine(i);
5. }

36 Prepared by Tesfa K. 5/15/2022


for loop statement…
For loop array traversal
 A for loop can be used for traversal of an array.
 From the Length property of the array we know the size of the array.
1. using System;
2. string[] planets = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus",
"Pluto" };
3. for (int i = 0; i < planets.Length; i++)
4. {
5. Console.WriteLine(planets[i]);
6. }
7. Console.WriteLine("In reverse:");
8. for (int i = planets.Length - 1; i >= 0; i--)
9. {
10. Console.WriteLine(planets[i]);
11. }

37 Prepared by Tesfa K. 5/15/2022


Nested for loop statement…
 For statements can be nested; i.e. a for statement can be placed inside another
for statement.
 All cycles of a nested for loops are executed for each cycle of the outer for
loop.
1. using System;
Output”
2. var a1 = new string[] { "A", "B", "C" };
AA
3. var a2 = new string[] { "A", "B", "C" }; AB
4. for (int i = 0; i < a1.Length; i++) AC
5. { BA
BB
6. for (int j = 0; j < a2.Length; j++) BC
7. { CA
8. Console.WriteLine(a1[i] + a2[j]); CB
CC
9. }
10. }
38 Prepared by Tesfa K. 5/15/2022
Nested for loop statement…
 Try the following patterns?
1. (a)
2. (b)
 * * * * *
 * * * * **
 * * * * ***
****
 * * * *
 * * * *
3. (c)
1
23
456
7 8 9 10
39 Prepared by Tesfa K. 5/15/2022
foreach statement
 The foreach construct simplifies traversing over collections of data.
 It has no explicit counter.
 The foreach statement goes through the array or collection one by one
and the current value is copied to a variable defined in the construct.
1. using System;
2. string[] planets = { "Mercury", "Venus", "Earth", "Mars",
"Jupiter","Saturn", "Uranus", "Neptune" };
3. foreach (string planet in planets)
4. {
5. Console.WriteLine(planet);
6. }

40 Prepared by Tesfa K. 5/15/2022


foreach statement…
1. int[] val = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 };
2. foreach (int num in val)
3. {
4. Console.WriteLine(num);
5. }

41 Prepared by Tesfa K. 5/15/2022


C# break statement:
 The break statement can be used to terminate a block defined by
while, for or switch statements.
1. using System;
2. var random = new Random();
3. while (true)
4. {
5. int num = random.Next(1, 30);
6. Console.Write("{0} ", num);
7. if (num == 22)
8. {
9. break;
10. }
11. }
12. Console.Write('\n');

42 Prepared by Tesfa K. 5/15/2022


C# continue statement:
 The continue statement is used to skip a part of the loop and continue with the next iteration
of the loop.
 It can be used in combination with for and while statements.
 In the following example, we print a list of numbers that cannot be divided by 2 without a
remainder (odds).
1. using System;
2. int num = 0;
3. while (num < 1000)
4. {
5. num++;
6. if (num % 2 == 0)
7. {
8. continue;
9. }
10. Console.Write("{0} ", num);
11. }
12. Console.Write('\n');

43 Prepared by Tesfa K. 5/15/2022


Methods and Their Types in C#
Passing parameters
 Types in C# are either value types or reference types.
 By default, both value types and reference types are
passed to a method by value.
Passing parameters by value:
 When a value type is passed to a method by value, a copy
of the object instead of the object itself is passed to the
method.
 Therefore, changes to the object in the called method
have no effect on the original object when control returns
to the caller.

44 Prepared by Tesfa K. 5/15/2022


Methods and Their Types in C#
1. using System;
2. public class Example
3. {
4. public static void Main()
5. { Output
6. int value = 20;
7. Console.WriteLine("In Main, value = {0}", value); In Main, value = 20
8. ModifyValue(value); In ModifyValue, parameter value = 30
9. Console.WriteLine("Back in Main, value = {0}", value); Back in Main, value = 20
10. }
11. static void ModifyValue(int i)
12. {
13. i =i+10;
14. Console.WriteLine("In ModifyValue, parameter value = {0}", i);
15. return;
16. }
17. }

45 Prepared by Tesfa K. 5/15/2022


Methods and Their Types in C#...
Passing parameters by reference
 You pass a parameter by reference when you want to
change the value of an argument in a method and want to
reflect that change in the calling method.
 To pass a parameter by reference, you use the ref or out
keyword.
 Example:-It is identical to the previous one, except the
value is passed by reference to the ModifyValue method.
 When the value of the parameter is modified in the
ModifyValue method, the change in value is reflected when
control returns to the caller.

46 Prepared by Tesfa K. 5/15/2022


Methods and Their Types in C#...
1. using System;
2. public class Example output:
3. {
In Main, value = 20
4. public static void Main() In ModifyValue, parameter value = 30
5. { Back in Main, value = 30
6. int value = 20;
7. Console.WriteLine("In Main, value = {0}", value);
8. ModifyValue(ref value);
9. Console.WriteLine("Back in Main, value = {0}", value);
10. }
11. static void ModifyValue(ref int i)
12. {
13. i = i+10;
14. Console.WriteLine("In ModifyValue, parameter value = {0}", i);
15. return;
16. }
17. }

47 Prepared by Tesfa K. 5/15/2022


End of Chapter Two

48 Prepared by Tesfa K. 5/15/2022

You might also like