Window Programming Ch3
Window Programming Ch3
Windows Programming
( C# )
1
CHAPTER 3
Object-Oriented Fundamentals
2
Variables and Data Types
3
Variables
4
Variables
6
Rules for naming variables in C#
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
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
byte 0 to 255
ushort 0 to 65,535
uint 0 to 4,294,967,295
ulong 0 to 18,446,744,073,709,551,615
-79228162514264337593543950335 to
decimal
79228162514264337593542950335
15
Value Type and Reference Type
16
Value Type
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
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
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
} }
26
If else Example2
27
Ternary operator
Example
int time = 20;
string result = (time < 18) ? "Good day." :
"Good evening.";
Console.WriteLine(result);
28
Nested If else
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
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
43
while loop
• 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
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.
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