0% found this document useful (0 votes)
48 views

Window Programming Ch3

The document provides information about variables and data types in C# programming. It discusses different types of variables like static, instance, and local variables. It also explains data types in C#, including value types and reference types. Key rules for naming variables and examples of declaring different variables are presented. Control structures like if, if-else, and nested if statements are also summarized.

Uploaded by

Abdurezak Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Window Programming Ch3

The document provides information about variables and data types in C# programming. It discusses different types of variables like static, instance, and local variables. It also explains data types in C#, including value types and reference types. Key rules for naming variables and examples of declaring different variables are presented. Control structures like if, if-else, and nested if statements are also summarized.

Uploaded by

Abdurezak Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 83

Ambo University Woliso Campus

School of Technology and Informatics


Department of Computer Science

Windows Programming
( C# )

1
CHAPTER 3

Object-Oriented Fundamentals

2
Variables and Data Types

 Variable is a location in the memory that has


name and value associated with it.
 C# is type – safe language.
 The compiler checks the value stored in the
variable is of the appropriate type.
 syntax to declare and initialize variables

<data_type> <variable_name> = <value>;

3
Variables

 example of variable declaration


int age = 12;
1. Static variable: A field with the static
modifier is called as static variable.
The initial value of the static variable is the
default value of the variable type.
public static int empno;

4
Variables

2. Instance variable: exists when a new


instance of the class is created by the user. The
initial value of the instance variable is the default
value of the variable type.
class message
{
int msg1;
int msg2;
}
5
Variables

3. Local variable: is declared by the local


variable declaration which can be a block,
control statements, lopping statements.
 The life of the local variable is the portion of
the program where the execution is specified.
 A local variable is not initialized automatically
and does not have any default value.

6
Rules for naming variables in C#

1) A variable must begin with a letter or an


underscore ( ‘_’ ) followed by the sequence of
letters, digits, or underscores.
2) The first character in the variable name cannot be
a digit.
3) It should not contain any spaces, symbols or
special character in the declaration like ? - +! # % ^ &
* ( ) [ ] { } . ; : " ' / and \.
4) It must be unique for every variable
5) The keywords cannot be used as variable names
7
Examples of variables in C#
namespace Variable
{
class Program
{
static void Main(string[] args)
{
string message = "Hello World!";
Console.WriteLine(message);
}
}
}
8
Examples of variables in C#

• Invalid Variable Assignment


string message = "Hello World!!";
int i = message;

int i;
int j = i; Console.WriteLine(j);
• You must assign a value to a variable before using it
otherwise the compiler will give an error.

9
C# Keywords

• Keywords are reserved words predefined to the


C# compiler.
• These keywords cannot be used as identifiers.
• However, if you want to use these keywords as
identifiers, you may prefix the keyword with the
@ character.
• In C#, some identifiers have special meaning in
context of code, such as get and set are called
contextual keywords.
10
11
12
C# Data types

• A variable must be declared with the data type


because C# is a strongly-typed language.
• The data type tells a C# compiler what kind of
value a variable can hold.
• C# includes many in-built data types for
different kinds of data, e.g., String, number,
float, decimal, etc.

13
Example: Data types

class Program
{
static void Main(string[] args)
{
string stringVar = "Hello World!!";
int intVar = 100;
float floatVar = 10.2f;
char charVar = 'A';
bool boolVar = true;
}}
14
Data type Ranges

Data Type Range

byte 0 to 255

sbyte -128 to 127

short -32,768 to 32,767

ushort 0 to 65,535

int -2,147,483,648 to 2,147,438,647

uint 0 to 4,294,967,295

long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

ulong 0 to 18,446,744,073,709,551,615

float -3.402823e38 to 3.402823e38

double -1.79769313486232e308 to 1.79769313486232e308

-79228162514264337593543950335 to
decimal
79228162514264337593542950335

char A Unicode character

string A string of Unicode characters

bool True or False

15
Value Type and Reference Type

• In C# data types are categorized based


on how they store their value in the
memory.
• C# includes following categories of data
types:
1. Value type
2. Reference type

16
Value Type

• A data type is a value type if it holds a


data value within its own memory space.
• It means variables of these data types
directly contain their values.

17
• To get the exact size of a type or a variable on a particular
platform, you can use the sizeof method.
• The expression sizeof(type) yields the storage size of the
object or type in bytes. E.g.

Output
Size of int: 4
18
Reference Type

A reference type doesn't store its value


directly. Instead, it stores the address
where the value is being stored. In other
words, a reference type contains a pointer
to another memory location that holds the
data.

19
 Example of built-in reference types are: object, dynamic,
and string.
a. Object Type
 Object is an alias for System.Object class.
 The object types can be assigned values of any other
types, value types, reference types, predefined or user-
defined types.
 However, before assigning values, it needs type
conversion.
 When a value type is converted to object type, it is called
boxing and when an object type is converted to a value
type, it is called unboxing. E.g. object obj;
obj = 100; // this is boxing
20
b. Dynamic Type
 You can store any type of value in the dynamic data type variable.
 Dynamic types are similar to object types. The d/ce is:
 Type checking for dynamic types of variables takes place at run-
time whereas, type checking for object type variables takes place
at compile time.
 Syntax for declaring a dynamic type is:
dynamic = value; For example, dynamic d = 20;
c. String Type
• The String Type allows you to assign any string values to a variable.
• The string type is an alias for the System.String class.
• It is derived from object type.
• The value for a string type can be assigned using string literals in
two forms: quoted and @quoted.
• E.g String str = "Tutorials Point"; OR @"Tutorials Point";21
C# Control Statements

22
If Statements

• It checks for the Boolean condition.


• A true statement is one that evaluates to a non - zero
number.
• A false statement evaluates to zero.
• The C# if statement tests the condition.
• It is executed if condition is true.

Syntax:
if(Condition is TRUE)
//EXECUTE this line of code
23
If Example

using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
Console.Read();
} }
24
If…else

• In an If else statement if condition evaluates to true,


then the statement1 is executed.
• If the condition is false, else statement2 is executed.
Syntax:
if(expression) {
statements1;
}
else {
statements2;
}
25
If else Example
public class IfExample {
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}
Console.Read();

} }

26
If else Example2

int time = 20;


if (time < 18)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}

27
Ternary operator

 Short Hand of If...Else


 variable = (condition) ? expressionTrue : expressionFalse;

 Example
int time = 20;
string result = (time < 18) ? "Good day." :
"Good evening.";
Console.WriteLine(result);

28
Nested If else

• An if...else statement can exist within another


if...else statement.
• Such statements are called nested if...else
statement.
• Nested if statements are generally used when
we have to test one condition followed by
another.
• In a nested if statement, if the outer if
statement returns true, it enters the body to
check the inner if statement.
29
Syntax of Nested If else
if (boolean-expression) {
if (nested-expression-1) {
// code to be executed
}
else {
// code to be executed
}}
else {
if (nested-expression-2) {
// code to be executed
}
else {
// code to be executed
}}

30
Nested If else Example

class Nested
{
public static void Main(string[] args)
{
int a = 7, b = -8, c = 15;
if (a > b)
{
if (a > c)
{
Console.WriteLine("{0} is the largest", a);
}
else
{
Console.WriteLine("{0} is the largest", b);
}
}

31
Nested If else
else
{
if (b > c)
{
Console.WriteLine("{0} is the largest", b);
}
else
{
Console.WriteLine("{0} is the largest", c);
}
}
Console.ReadKey();
}
}
Output:
15 is the largest

32
If else If ladder Statement
 The C# if-else-if ladder statement executes one
condition from multiple statements.
 Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
else{
//code to be executed if all the conditions are false
}
33
If else If Example
public class Grade
{
public static void Main(string[] args)
{
Console.WriteLine("Enter your mark out of 100 to check grade:");
Double mark = Convert.ToDouble(Console.ReadLine());
if (mark < 0 || mark > 100)
{
Console.WriteLine("No such Mark");
}
else if (mark >= 0 && mark < 50)
{
Console.WriteLine("F");
}

34
If else If Example
else if (mark >= 50 && mark < 60)
{
Console.WriteLine("Your Grade is D");
}
else if (mark >= 60 && mark < 70)
{
Console.WriteLine("Your Grade is C");
}
else if (mark >= 70 && mark < 80)
{
Console.WriteLine("Your Grade is B");

35
If else If Example
else if (mark >= 80 && mark < 90)
{
Console.WriteLine("Your Grade is A");
}
else if (mark >= 90 && mark <= 100)
{
Console.WriteLine("Your Grade is A+");
}
Console.ReadKey();
}
}
}
Output:
Enter your mark out of 100 to check grade:
78.5
Your Grade is B
36
Switch statement

The switch statement is used when you have to evaluate


a variable for multiple values.
Syntax:
switch ( variablename ) {
case constantExpression_1:
statements;
break;
case constantExpression_2:
statements;
break;
default:
statements;
break;
}

37
Switch Example
class Program
{
static void Main(string[] args)
{
string month, season;
Console.WriteLine("Please enter month to know its season");
month = Console.ReadLine();
switch (month)
{
case "December":
case "January":
case "February":
season = "Winter";
break;

38
Switch Example
case "March":
case "April":
case "May":
season = "Spring";
break;
case "June":
case "July":
case "August":
season = "Summer";
break;
case "September":
case "October":
case "November":
season = "Autumn";
break;

39
Switch Example
default:
season = "Unknown";
break;
}
Console.WriteLine(month+" is in " + season +" season");
Console.ReadKey();
}
}

Output:
Please enter month to know its season
April
April is in Spring season

40
Break statements
• The break statement terminates the case in the switch
statement where it is placed.
• Control is passes to the statement followed by the terminated
statement if present in the loop.
Code snippet
class Program {
static void Main ( string [ ] args ) {
for ( int i=0; i<=10; i++ )
{
if ( i==4) {
break;
}
Console.WriteLine(i);
}
Console.Read();
}
}
Ex: Write a program w/c displays numbers from 20 to 40, except 25 & 35
41
continue statements
• The continue statement is used to pass the control to the next
iteration for the statement in which it appears.
Code snippet
class Program {
static void Main ( string [ ] args ) {
for ( int i=0; i<=10; i++) {
if(i<6)
{
continue;
}
Console.WriteLine(i);
}
Console.Read();
}
}

42
while loop

• The while loop statement is used to execute a


block depending on the condition specified.
• The condition is checked first and the
statements within the loop are executed if the
condition returns true.
• After the last statement in the while loop is
executed, the control is sent back to the start of
the loop.

43
while loop

• When the condition is true, the statements present in


the loop are executed.
• The execution of the loop stops when the condition
returns a false value.

• Syntax
while ( expression )
{
statements;
}
44
while loop

• Code Snippet
• Write C# program which displays number divisible by 5 b/n 10 & 30 and their remainder is 0.
class Program
{
static void Main ( string[ ] args )
{
int i = 1;
while ( i<10 )
{
Console.WriteLine(“Value of the variable is :{0}”, i );
i= i+2;
}
Console.Read();
}
}

45
Do while loop

• The do while loop and while loop are similar.


• But the statements in the do while loop are executed
at least once, as they are executed before the
condition is checked.
• The d/c b/n while & do while loop

46
Do while loop

Syntax:

do
{
statements;
} while ( expression );

47
Do while loop

Code snippet:
class Program
{
static void Main ( string[ ] args )
{
int i=10;
do
{
Console.WriteLine(“value of i is”+i);
i = i+10;
} while ( i<100 );
Console.Read();
}
}
48
for loop
• A for loop structure is used to execute a set of statements for a
specified number of times.
• Syntax:
for ( initialization; termination; increment/decrement)
{
Statements
}

49
for loop

sample code:
static void Main ( string [] args )
{
int i;
for ( i=50; i<=60; i++ )
{
Console.WriteLine( “Value of variable i is “+i);
}
Console.Read();
}

50
C# Inheritance
• Inheritance is an important pillar of OOP.
• It is the mechanism in C# by which one class is
allowed to inherit the features (fields and methods) of
another class.
• Important terminology:
• Super Class: The class whose features are inherited is
known as super class (or a base class or a parent class).
• Sub Class: The class that inherits the other class is
known as subclass (or a derived class, extended class,
or child class).
51
• The subclass can add its own fields and methods in
addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of
“reusability”, i.e. when we want to create a new class.
• By doing this, we are reusing the fields and methods
of the existing class.

• The symbol used for inheritance is: Syntax:


class derived-class : base-class
{
// methods and fields
}

52
53
54
C# Encapsulation
• Encapsulation is defined as the wrapping up of data
under a single unit.
• It is the mechanism that binds together code and the
data it manipulates.
• In a different way, encapsulation is a protective shield
that prevents the data from being accessed by the code
outside this shield.
• Technically in encapsulation, the variables or data of a
class are hidden from any other class and can be
accessed only through any member function of own
class in which they are declared.
55
• As in encapsulation, the data in a class is hidden from
other classes, so it is also known as data-hiding.
• Encapsulation can be achieved by: Declaring all the
variables in the class as private and using C# Properties
in the class to set and get the values of variables.

56
57
58
• Explanation: In the above program the class Encap is
encapsulated as the variables are declared as private.
• To access these private variables we are using the Name and
Age accessors which contains the get and set method to retrieve
and set the values of private fields.
• Accessors are defined as public so that they can access in other
class.
Advantages of Encapsulation:
• Data Hiding: The user will have no idea about the inner
implementation of the class.
• It will not be visible to the user that how the class is stored
values in the variables.
• He only knows that we are passing the values to accessors and
variables are getting initialized to that value.

59
• Increased Flexibility: We can make the variables of the
class as read-only or write-only depending on our
requirement.
• If we wish to make the variables as read-only then we
have to only use Get Accessor in the code.
• If we wish to make the variables as write-only then we
have to only use Set Accessor.
• Reusability: Encapsulation also improves the re-
usability and easy to change with new requirements.
• Testing code is easy: Encapsulated code is easy to test
for unit testing.

60
C# Abstraction
• Data Abstraction is the property by virtue of which
only the essential details are exhibited to the user.
• The trivial or the non-essentials units aren’t exhibited
to the user.
• Data Abstraction may also be defined as the process of
identifying only the required characteristics of an
object ignoring the irrelevant details.
• The properties and behaviour's of an object
differentiate it from other objects of similar type and
also help in classifying/grouping the objects.

61
• Example: Consider a real-life scenario of withdrawing
money from ATM.
• The user only knows that in ATM machine first enter
ATM card, then enter the pin code of ATM card, and
then enter the amount which he/she wants to withdraw
and at last, he/she gets their money.
• The user does not know about the inner mechanism of
the ATM or the implementation of withdrawing money
etc.
• The user just simply know how to operate the ATM
machine, this is called abstraction.
• In C# abstraction is achieved with the help of Abstract
classes.
62
Abstract Classes
• An abstract class is declared with the help of abstract keyword.
• In C#, you are not allowed to create objects of the abstract class. Or in
other words, you cannot use the abstract class directly with the new
operator.
• Class that contains the abstract keyword with some of its methods
(not all abstract method) is known as an Abstract Base Class.
• Class that contains the abstract keyword with all of its methods is
known as pure Abstract Base Class.
• You are not allowed to declare the abstract methods outside the
abstract class.
• You are not allowed to declare abstract class as Sealed Class.

63
Output:
Area of Square: 16
64
Encapsulation vs Data Abstraction
• Encapsulation is data hiding (information hiding) while
Abstraction is detail hiding (implementation hiding).
• While encapsulation groups together data and methods
that act upon the data, data abstraction deals with
exposing to the user and hiding the details of
implementation.
Advantages of Abstraction
• It reduces the complexity of viewing the things.
• Avoids code duplication and increases reusability.
• Helps to increase security of an application or program as
only important details are provided to the user.
65
C# Methods
• A method is a collection of statements that perform
some specific task and return the result to the caller.
• A method can also perform some specific task without
returning anything. e.g
static double GetCircleArea(double radius)
{
const float pi = 3.14F;
double area = pi * radius * radius;
return area;
}
66
• Method declaration means the way to construct method
including its naming.

67
Output: The sum is: 35
68
69
Advantages of using the Methods:
• It makes the program well structured.
• Methods enhance the readability of the code.
• It provides an effective way for the user to reuse the
existing code.
• It optimizes the execution time and memory space.

70
C# Method Overriding
• Method Overriding is a technique that allows the
invoking of functions from another class (base class) in
the derived class.
• Creating a method in the derived class with the same
signature as a method in the base class is called as method
overriding. When a method in a subclass has the same
name, same parameters or signature and same return
type(or sub-type) as a method in its super-class, then the
method in the subclass is said to override the method in
the super-class.
• Method overriding is one of the ways by which C#
achieve Run Time Polymorphism (Dynamic
Polymorphism). 71
• The method that is overridden by an override
declaration is called the overridden base method.
• An override method is a new implementation of a
member that is inherited from a base class.
• The overridden base method must be virtual, abstract,
or override.

72
73
a m ily
t h e F il d
i s
s i t he C h
h
p ut: T i s i s
Out Th

74
Note:
• Method overriding is possible only in derived classes.
• Because a method is overridden in the derived class
from base class.
• A method must be a non-virtual or static method for
override.
• Both the override method and the virtual method must
have the same access level modifier

75
C# Method Overloading
• Method Overloading is the common way of implementing
polymorphism.
• It is the ability to redefine a function in more than one
form.
• A user can implement function overloading by defining
two or more functions in a class sharing the same name.
• C# can distinguish the methods with different method
signatures. i.e. the methods can have the same name but
with different parameters list (i.e. the number of the
parameters, order of the parameters, and data types of the
parameters) within the same class.
76
• Overloaded methods are differentiated based on the
number and type of the parameters passed as arguments
to the methods.
• You cannot define more than one method with the same
name, Order and the type of the arguments. It would be
compiler error.
• The compiler does not consider the return type while
differentiating the overloaded method.
• But you cannot declare two methods with the same
signature and different return type.
• It will throw a compile-time error.
• If both methods have the same parameter types, but
different return type, then it is not possible.
77
• Different ways of doing overloading methods
1. The number of parameters in two methods.
2. The data types of the parameters of methods.
3. The Order of the parameters of methods.

78
79
80
81
82
Thank you

83

You might also like