0% found this document useful (0 votes)
33 views45 pages

CH 2

Uploaded by

Markos Mathewos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views45 pages

CH 2

Uploaded by

Markos Mathewos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Chapter Two

 Language Fundamentals in C#
 Object Oriented Concepts(Class and objects)
 Object-Oriented Fundamentals in C#

C# Fundamentals 1
 Language Fundamentals in C#
Working with Variables and Data Types
 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.
 A variable is a memory location where a value is stored. Using the variable, your
program can read or alter the value stored in memory.
 Variables must be declared before use.
 When it is declared a compiler knows what kind of data will be stored at the
memory location.
 For example, will it be numbers or letters? If the variable will store numbers, how
large can a number be?
 Will the variable store decimals or only whole numbers? You answer these
questions by assigning a data type to the variable.

C# Fundamentals 2
Working with Variables and Data Types

 Define variables to hold data.

 Variables can represent numeric values, characters, character strings, or memory addresses.

 Variables represent storage locations in memory.

 Variables are of a specific data type.

 A variable declaration reserves memory space for the variable and may optionally specify an
initial value.

 Ex

C# Fundamentals 3
Continued …

The variables in C#, are categorized into the following types:


1. Value types
2. Reference types

C# Fundamentals 4
1. Value Type
 Value type variables can be assigned a value directly. They are derived from the
class System.ValueType.

C# Fundamentals 5
2. Reference type
 In contrast to the value type, a reference type doesn’t directly hold values.
 Instead of directly holding the value it holds the address where the value might be stored.
 In simple words, a reference type variable just holds a reference to a particular memory
location that may hold the required data.
 Some of the reference type data include string, arrays, class, etc.
 Hence, if any changes are made to the data then the other variable will automatically
inherit the new changed value and 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

C# Fundamentals 6
Object type
 An object data type is a 32-bit address that points to the memory location of another data type.
 It is commonly used to declare variables when the actual data type they refer to can’t be
determined until runtime.
 Every type in C# derives from the object class type, whether directly or indirectly.
 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. }
C# Fundamentals 7
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
Dynamic MyDynamicVar = 1;
Console.WriteLine(MyDynamicVar.GetType());
Output: System.Int32

C# Fundamentals 8
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. }

C# Fundamentals 9
Console Statement
• It is a command line interface which is used to display an out put and to take inputs from the key
board. Example

Console.WriteLine(“Hello C#"); //to display output

string username=Console.ReadLine();//to take inputs

int value1=Convert.ToInt32(Console.ReadLine()); //take int type

C# Fundamentals 10
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:
It is also possible to write like this to
1. using System; avoid the whole unsafe
1. unsafe
2. namespace PointerDemo {
2. {
3. class Example { 3. int val = 100;
4. static unsafe void Main(string[] args) 4. int* ptr = &val;
5. { 5. Console.WriteLine("Data is: {0} ", val);
Console.WriteLine("Address is: {0} ",
6. int val = 100; (int)ptr);
7. int* ptr = &val; 6. }
8. Console.WriteLine("Data value is: {0} ", val);
9. Console.WriteLine("Address of the data value is: {0}", (int)ptr);
10. }
11. }
C# Fundamentals 11
12. }
Control Flows in C#
 Control flow (or alternatively, flow of control) refers to the order in which the
individual statements, instructions or function calls of an imperative or a
declarative program are executed or evaluated.
 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 of the source
file to the bottom. One by one.
 This flow can be altered by specific keywords. Statements can be executed
multiple times.
 Some statements are called conditional statements. They are executed only if
a specific condition is met.

C# Fundamentals 12
Control Flows in C#...
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.

C# Fundamentals 13
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. }

C# Fundamentals 14
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. } else
9. {
10. Console.WriteLine("The number is negative"); // returns -ve value
11. }

C# Fundamentals 15
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. }
C# Fundamentals 16
C# Loop Statement

 While 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:
1. while (expression)
2. {
3. statement;
4. }
 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.

C# Fundamentals 17
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.

C# Fundamentals 18
 Do-while 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 count = 0;
3. do {
4. Console.WriteLine(count);
5. } while (count != 0);
 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.

C# Fundamentals 19
 for 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. }

C# Fundamentals 20
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.} C# Fundamentals 21
C# for statement…
 Nested for loops:
 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.
using System;
1. var a1 = new string[] { "A", "B", "C" };
2. var a2 = new string[] { "A", "B", "C" };
3. for (int i = 0; i < a1.Length; i++)
4. {
5. for (int j = 0; j < a2.Length; j++)
6. {
7. Console.WriteLine(a1[i] + a2[j]);
8. }
9. }
C# Fundamentals 22
 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. }
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. }

C# Fundamentals 23
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'); C# Fundamentals 24
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($"{num} ");
11. }
12. Console.Write('\n'); C# Fundamentals 25
 Object Oriented Concepts(Class and objects)
Why Use OOP?
 Why OOP developed into such a widely used paradigm for solving business
problems today?
 This was an improvement, but as programs performed more complex business
functionality and interacted with other systems, the following shortcomings of
structural programming began to surface:
 Programs became harder to maintain.
 Existing functionality was hard to alter without adversely affecting all of the system’s
functionality.
 New programs were essentially built from scratch. Consequently, there was little return on the
investment of previous efforts.
 The main advantages of OOP are to make complex software faster to develop
and easier to maintain.
 OOP enables the easy reuse of code by applying simple and widely accepted
rules (principles).
C# Fundamentals 26
Object-Oriented Concepts…
 As a result, many business software developers turned to object-oriented methods
and programming languages.
 The benefits included the following:
 A more intuitive transition from business-analysis models to software-implementation models,

 The ability to maintain and implement changes in the programs more efficiently and rapidly,

 The ability to create software systems more effectively using a team process, allowing
specialists to work on parts of the system,
 The ability to reuse code components in other programs and purchase components written by
third-party developers to increase the functionality of existing programs with little effort,
 better integration with loosely coupled distributed-computing systems,

 improved integration with modern operating systems,

 the ability to create a more intuitive graphical-user interface for the users
C# Fundamentals 27
Concepts of OOP:
 Objects
 Classes
 Data Abstraction and Encapsulation
 Inheritance
 Polymorphism

C# Fundamentals 28
Class:
 In the real world, every object has some color, shape, and functionalities.
 Likewise, in object-oriented programming, a class defines some properties, fields, events,
methods, etc.
 A class defines the kinds of data and the functionality their objects will have.
 A class enables you to create your custom types by grouping variables of other types, methods,
and events.
 In C#, a class can be defined by using the class keyword.
Objects:
 In OOP terms, an object is a structure for incorporating data and the procedures for working
with that data.
 For example, if you were interested in tracking data associated with product inventory, you
would create a product object that is responsible for maintaining and using the data pertaining
to the products.

C# Fundamentals 29
C# Fundamentals 30
 In order for a programming language to be object-oriented, it has to
enable working with classes and objects as well as the implementation
and use of the fundamental object-oriented principles and concepts:
Inheritance,
Abstraction,
Encapsulation and
Polymorphism.

C# Fundamentals 31
 Object-Oriented Fundamentals in C#(Implementation)
Inheritance:
 is the process by which one object acquires the properties of another object.
A type derives from a base type, taking all the base type members fields and
functions.
 Inheritance is most useful when you need to add functionality to an existing
type. For example all .NET classes inherit from the System.Object class, so a
class can include new functionality as well as use the existing object's class
functions and properties as well.

The syntax of inheritance;


• Class derivedClass : baseClass{ body }
C# Fundamentals 32
1. using System;
1. class Inheritance
2. namespace oops
2. {
3. {
3. static void Main(string[] args)
4. //Base Class
4. {
5. public class Father
6. {
5. Father fObj = new Father();
7. public void FatherMethod()
6. fObj.FatherMethod();
8. {
//Here Child object can access both class methods
9. Console.WriteLine("this property belong to Father");
10. }
7. Child cObj = new Child();
11. }
8. cObj.FatherMethod();
9. cObj.ChildMethod();
12. //Derived class
10. }
13. public class Child : Father
11. }
14. {
15. public void ChildMethod() Try this: by applying multiple inheritances:
16. {  Animal eats()=>base class
17. Console.WriteLine("this property belong to Child");  Dog barks()=>derived
18. }  Cow moos()=> >>
19. }  Cat meows()=> >>
20. }
C# Fundamentals 33
Encapsulation:
 Encapsulation is one of the main concepts in OOP.
 It is also called "information hiding".
 An object has to provide its users only with the essential information
for manipulation, without the internal details.
 A Secretary using a Laptop only knows about its screen, keyboard and
mouse. Everything else is hidden internally under the cover.
 She does not know about the inner workings of Laptop, because she
doesn’t need to, and if she does, she might make a mess.
 Therefore parts of the properties and methods remain hidden to her.

C# Fundamentals 34
Encapsulation…

C# Fundamentals 35
Encapsulation…

1. public class Lion : Felidae


2. {
3. private Paw frontLeft;
4. private Paw frontRight;
5. private Paw bottomLeft;
6. private Paw bottomRight;
7. private void MovePaw(Paw paw)
8. {
9. //
10.}
11.public override void Walk()
12.{
13.this.MovePaw(frontLeft);
14.this.MovePaw(frontRight);
15.this.MovePaw(bottomLeft);
16.this.MovePaw(bottomRight);
17.}
18.}

C# Fundamentals 36
Encapsulation…

In the above scenario,

 The public method Walk() calls some other private method 4 times.

 That way the base class is short – it consists of a single method.

 The implementation, however, calls another of its methods, which is hidden from the
users of the class.

 That way, Lion doesn’t publicly disclose information about its inner workings (it
encapsulates certain behavior).

 At a later stage, this makes it possible to change its implementation without any of the
other classes finding out and requiring changes.

C# Fundamentals 37
Polymorphism
 The condition of occurring in several different forms.

 polymorphism allows treating objects of a derived class as objects of its base class.

 For example, big cats (base class) catch theirprey (a method) in different ways.

 A Lion (derived class) sneaks on it, while a Cheetah (another derived class) simply outruns it.

 Polymorphism allows us to treat a cat of random size just like a big cat and command it "catch your
prey", regardless of its exact size.

 Polymorphism can bear strong resemblance to abstraction, but it is mostly related to overriding
methods in derived classes, in order to change their original behavior inherited from the base class.

 Abstraction is associated with creating an interface of a component or functionality (defining a


role).

C# Fundamentals 38
1. class Animal // Base class (parent) 15.class Dog : Animal // Derived class (child)
16. {
2. {
17. public override void animalSound()
3. public virtual void animalSound() 18. {
19. Console.WriteLine("The dog says: bow wow");
4. { 20. }
5. Console.WriteLine("The animal’s sound"); 21. }
22.class Program
6. } 23. {
7. } 24. static void Main(string[] args)
25. {
8. class Pig : Animal//Derived class (child) 26. Animal myAnimal = new Animal();//Create Anml obj
9. { 27. Animal myPig = new Pig(); // Create a Pig object
28. Animal myDog = new Dog(); // Create a Dog object
10. public override void animalSound() 29. myAnimal.animalSound();
11. { 30. myPig.animalSound();
31. myDog.animalSound();
12. Console.WriteLine("The pig says: wee 32. }
wee"); 33. }
13. }
14. }

C# Fundamentals 39
Abstract Class
 This is accomplished by putting the keyword abstract before the name of the class
and indicates that the class is not ready to be instantiated.

 Abstraction in C# is the process to hide the internal details and showing


functionality only.

 We refer to such classes as abstract classes.

 Typically used to define a base class in the class hierarchy.

 Is an incomplete class or special class we can’t be instantiated.

C# Fundamentals 40
Here is how the implementation of the above abstraction looks like:
Lion.cs

7. public override bool CatchPrey(object prey)


1. public class Lion : Felidae { 8. {
2. protected void Ambush() 9. base.Hide();
3. { 10. this.Ambush();
4. // … 11. base.Run();
5. } 12. // …
13. return false;
14. }
15. }

C# Fundamentals 41
Abstract Method
A method which is declared abstract and has no body is called abstract method. It
can be declared inside the abstract class only. Its implementation must be provided
by derived classes. For example:
1. using System; 20. public class TestAbstract
2. public abstract class Shape
3. {
21. {
4. public abstract void draw(); 22. public static void Main()
5. } 23. {
6. public class Rectangle : Shape 24. Shape s;
7. { 25. s = new Rectangle();
8. public override void draw() 26. s.draw();
9. { 27. s = new Circle();
10. Console.WriteLine("drawing rectangle...");
28. s.draw();
11. }
12. }
29. }
13. public class Circle : Shape 30. }
14. {
15. public override void draw()
16. {
17. Console.WriteLine("drawing circle...");
18. }
19. }
C# Fundamentals 42
Practice at your lab
Implement the following points covered from this chapter in your lab schedule and
adapt it to your respective projects!
1. Abstract class through interface implementation,
2. Inheritance (simple, multilevel, multiple through interface)
3. Method overriding through polymorphism
4. Parameters passing by values and references

C# Fundamentals 43
Lab Exercise-2
A company pays its employees on a weekly basis. The employees are of four types:
a) Salaried employees are paid a fixed weekly salary regardless of the number of hours worked
b) Hourly employees are paid by the hour and receive overtime pay for all hours worked in excess
of 40 hours
c) Commission employees are paid a percentage of their sales
d) Salaried-Commission employees receive a base salary plus a percentage of their sales.
For the current pay period, the company has decided to reward salaried-commission employees by
adding 10% to their base salaries.
The company wants to implement a C# application that performs its payroll calculations.
1. Design the class Diagram.
2. Implement the code to fulfil the requirement in C# language.

C# Fundamentals 44
The end!

C# Fundamentals 45

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy