SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
Visual C# .Net using
framework 4.5
Eng. Mahmoud Ouf
Lecture 03
mmouf@2018
Array
Arrays are sequence of data of the same data type. You can access an
individual element of an array by means of its position (index).
In C#, array notation is very similar to that used by C/C++ but it differs
in two things:
• You can't write square brackets to the right of the variable name.
• You DON'T specify the size of array when declaring it.
All C# array are derived from the System.Array base class.
To define an array, this is done in 2 steps:
1. declare array
2. create array
The general form of declaring an array:
Data_type[] array_name;
The size of an array is established when it is created not when it is
declared.
mmouf@2018
Array
• In C#, an array element access expression is automatically
checked to ensure that the index is valid. This is used to ensure that C#
is a type safe language. Otherwise, it will throw OutofRangeException.
• We can't shrink or expand the array
• Declaring an array doesn't mean creating an array instance, this is
because array are reference type not value type.
• The array are implicitly initialized by 0 or false if it is of type
boolean.
• When initializing array, you must explicitly initialize all array
element.
mmouf@2018
Single Dimension Array
string[] books; //declare
books = new string[3]; //create array of 3 element
OR
Books = new string[3] {"C#", "DotNet", "VB.Net"}; //create and init
OR(Declare and create at 1 step)
string[] books = {"C#", "DotNet", "VB.Net"}; //will set the array 3
OR(Declare and create at 1 step)
string[] books = new string[3]{"C#", "DotNet", "VB.Net"};
mmouf@2018
Two Dimension Array
int[,] grid;
grid = new int [2, 3];
grid[0, 0] = 5;
grid[0, 1] = 4;
grid[0, 2] = 3;
grid[1, 0] = 2;
grid[1, 1] = 1;
grid[1, 2] = 2;
Create and initialize:
int[,] grid = {{5, 4, 3}, {2, 1, 0}};
OR
int[,] grid = new int[2, 3]{{5, 4, 3}, {2, 1, 0}};
mmouf@2018
Two Dimension Array
Declaration is important in compilation. While creation is done at
runtime
So, you can make the size of array variable, which is very similar to
Dynamic allocation.
Example:
int rows;
int col;
Console.WriteLine(“Enter number of rows”);
rows = int.Parse(Console.ReadLine());
Console.WriteLine(“Enter number of columns”);
col = int.Parse(Console.ReadLine());
int[,] ar;
ar = new int[rows, col];
mmouf@2018
Jagged Array
C# also allows you to create a special type of two-dimensional array
called a jagged array.
A jagged array is an array of arrays in which the length of each array
can differ.
A jagged array can be used to create a table in which the lengths of the
rows are not the same.
Jagged arrays are declared by using sets of square brackets to indicate
each dimension.
For example, to declare a two-dimensional jagged array, you will use
this general form:
type[ ] [ ] array-name = new type[size][ ];
Here, size indicates the number of rows in the array.
The rows, themselves, have not been allocated. Instead, the rows are
allocated individually. This allows for the length of each row to vary.
mmouf@2018
Jagged Array
Example:
int[][] jagged = new int[3][];
jagged[0] = new int[4];
jagged[1] = new int[3];
jagged[2] = new int[5];
Once a jagged array has been created, an element is accessed by
specifying each index within its own set of brackets.
For example, to assign the value 10 to element 2, 1 of jagged, you
would use this statement:
jagged[2][1] = 10;
mmouf@2018
Properties of Array
Length: returns number of element in the array.
Example:
int[] x;
x = new int[7];
int y = x.Length; //y = 7
int[,] a;
a = new int[3, 4];
int b = a.Length; //b = 12 (3*4)
Rank: return the dimension of array
Example:
int z = x.Rank; //z = 1;
int c = a.Rank; //c = 2;
mmouf@2018
Properties of Array
Sort(): sort an array
System.Array.Sort(array_name); //sort the array
Clear(): set a range of elements in the array to zero, false or null
reference
System.Array.Clear(array_name, starting_index, numberofelement);
Clone(): this method creates a new array instance whose elements are
copies of the elements of the cloned array.
int[] cl = (int[])data.Clone();
If the array being copied contains references to objects, the
references will be copied and not the objects. Both arrays will refer to
the same objects
mmouf@2018
Properties of Array
GetLength(): this method returns the length of a dimension provided as
an integer.
Ex: int [,] data = {{0, 1, 2, 3}, {4, 5, 6, 7}};
int dim0 = data.GetLength(0); //2
int dim1 = data.GetLength(1); //4
IndexOf(): this method returns the integer index of the first occurrence
of a value provided as argument or -1 if not found. (used in 1-dimension
array)
int[] data = {4, 6, 3, 8, 9, 3};
int Loc – System.Array.IndexOf(data, 9); //4
A method may return array:
mmouf@2018
Properties of Array
The C# allows you to iterate over all items within a collection (ex:
array,…)
int []ar = new int[]{0, 1, 2, 3, 4, 5};
foreach(int I in ar)
{
Console.WriteLine(i);
}
You can’t modify the elements in a collection by using a foreach
statement because the iteration variable is implicitly readonly.
foreach(int i in ar)
{
i++ ; //compile time error
Console.WriteLine(i);
}
mmouf@2018
Implicitly Typed Local Variables and Arrays
We can declare any local variable as var and the type will be inferred by
the compiler from the expression on the right side of the initialization
statement.
This inferred type could be:
Built-in type
User-defined type
Type defined in the .NET Framework class library
Example:
var int_variable = 6; // int_variable is compiled as an int
var string_variable = “Aly"; // string_variable is compiled as a string
var int_array = new[] { 0, 1, 2 }; // int_array is compiled as int[]
var int_array = new[] { 1, 10, 100, 1000 }; // int[]
var string_array = new[] { "hello", null, "world" }; // string[]
mmouf@2018
Implicitly Typed Local Variables and Arrays
Notes:
• var can only be used when you are to declare and initialize the local
variable in the same statement.
• The variable cannot be initialized to null.
• var cannot be used on fields at class scope.
• Variables declared by using var cannot be used in the initialization
expression. In other words, var i = i++; produces a compile-time error.
• Multiple implicitly-typed variables cannot be initialized in the same
statement.
• var can’t be used to define a return type
• Implicit typed data is strongly typed data, variable can’t hold values of
different types over its lifetime in a program
mmouf@2018
Classes
Class is a named syntactic construct that describes common behavior
and attribute.
All classes are reference type and inherit from object class directly or
indirectly.
There is also: class variable( or static members).
Ex:
class MyClass
{
private int x;
public int GetX()
{
return x;
}
}
mmouf@2018
Classes
Each member in the class (class member or static member) must have
an access modifier (public, private or protected)
The class itself is a template, so to deal with the class we must have an
object from this class.
To have an object of a class:
1) Declaration : MyClass m;
2) Creation : m = new MyClass(); //Done at run time.
Note: object of a class is a reference type.
mmouf@2018
Classes
Passing Reference type variable to a function:
Ex:
class C1
{
public int a;
}
class C2
{
public void MyFunction(C1 x)
{
x.a = 20;
}
}
mmouf@2018
Classes
class C3
{
public static void Main()
{
C1 L;
C2 M;
L = new C1();
L.a = 5;
M = new C2();
M.MyFunction(L);
Console.WriteLine(L.a); // 20
}
}
With reference type variable: either call by value or call by reference it will be
considered as a call by reference
The this object is sent in calling the function of an object, it is the reference to the
calling object. mmouf@2018
Static Classes
C# 2.0 added the ability to create static classes.
There are two key features of a static class.
First, no object of a static class can be created.
Second, a static class must contain only static members.
The main benefit of declaring a class static is that it enables the
compiler to prevent any instances of that class from being created.
Thus, the addition of static classes does not add any new functionality to
C#.
Within the class, all members must be explicitly specified as static.
Making a class static does not automatically make its members static.
mmouf@2018
String Class
1) Insert: insert characters into string variable and return the new
string
Ex: String S = “C is great”
S = S.Insert(2, “Sharp”);
Console.WriteLine(S); //C Sharp is great
2) Length : return the length of a string.
Ex : String msg = “Hello”;
int slen = msg.Length;
3) Copy: creates new string by copying another string (static)
Ex: String S1 = “Hello”;
String S2 = String.Copy(S1);
4) Concat: Creates new string from one or more string (static)
Ex: String S3 = String.Concat(“ä”, “b”, “c”, “d”); or use + operator
S3 = “a” + “b” + “c” +”d”;
mmouf@2018
String Class
5) ToUpper, ToLower: return a string with characters converted
upper or lower
Ex: String sText = “Welcome”;
Console.WriteLine(sText.ToUpper()); //WELCOME
6) Compare: compares 2 strings and return int.(static)
-ve (first<second) 0 (first = second) +ve (first>second)
Ex:String S1 = “Hello”; S2 = “Welcome”;
int comp = String.Compare(S1, S2); //-ve
there is another version of Compare that takes 3 parameters, the
third is a boolean :true (ignore case) false (Check case)
mmouf@2018

Mais conteúdo relacionado

Mais procurados (20)

Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Intake 37 5
Intake 37 5Intake 37 5
Intake 37 5
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
 
Intake 37 2
Intake 37 2Intake 37 2
Intake 37 2
 
Intake 37 1
Intake 37 1Intake 37 1
Intake 37 1
 
Intake 38_1
Intake 38_1Intake 38_1
Intake 38_1
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Intake 38 7
Intake 38 7Intake 38 7
Intake 38 7
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
C sharp chap4
C sharp chap4C sharp chap4
C sharp chap4
 
Templates
TemplatesTemplates
Templates
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Java execise
Java execiseJava execise
Java execise
 
Basic c#
Basic c#Basic c#
Basic c#
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
 
C# Generics
C# GenericsC# Generics
C# Generics
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 

Semelhante a Intake 38 3 (20)

Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
 
Arrays
ArraysArrays
Arrays
 
C# p9
C# p9C# p9
C# p9
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
Structures
StructuresStructures
Structures
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Array
ArrayArray
Array
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Java part 2
Java part  2Java part  2
Java part 2
 
C#ppt
C#pptC#ppt
C#ppt
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 

Mais de Mahmoud Ouf

Mais de Mahmoud Ouf (17)

Relation between classes in arabic
Relation between classes in arabicRelation between classes in arabic
Relation between classes in arabic
 
Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4
 
Intake 38 data access 1
Intake 38 data access 1Intake 38 data access 1
Intake 38 data access 1
 
Intake 38 11
Intake 38 11Intake 38 11
Intake 38 11
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Intake 37 DM
Intake 37 DMIntake 37 DM
Intake 37 DM
 
Intake 37 ef1
Intake 37 ef1Intake 37 ef1
Intake 37 ef1
 
Intake 37 linq3
Intake 37 linq3Intake 37 linq3
Intake 37 linq3
 
Intake 37 linq2
Intake 37 linq2Intake 37 linq2
Intake 37 linq2
 
Intake 37 linq1
Intake 37 linq1Intake 37 linq1
Intake 37 linq1
 
Intake 37 12
Intake 37 12Intake 37 12
Intake 37 12
 
Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
 
Intake 37 10
Intake 37 10Intake 37 10
Intake 37 10
 
Intake 37 9
Intake 37 9Intake 37 9
Intake 37 9
 
Intake 37 8
Intake 37 8Intake 37 8
Intake 37 8
 

Último

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 

Último (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

Intake 38 3

  • 1. Visual C# .Net using framework 4.5 Eng. Mahmoud Ouf Lecture 03 mmouf@2018
  • 2. Array Arrays are sequence of data of the same data type. You can access an individual element of an array by means of its position (index). In C#, array notation is very similar to that used by C/C++ but it differs in two things: • You can't write square brackets to the right of the variable name. • You DON'T specify the size of array when declaring it. All C# array are derived from the System.Array base class. To define an array, this is done in 2 steps: 1. declare array 2. create array The general form of declaring an array: Data_type[] array_name; The size of an array is established when it is created not when it is declared. mmouf@2018
  • 3. Array • In C#, an array element access expression is automatically checked to ensure that the index is valid. This is used to ensure that C# is a type safe language. Otherwise, it will throw OutofRangeException. • We can't shrink or expand the array • Declaring an array doesn't mean creating an array instance, this is because array are reference type not value type. • The array are implicitly initialized by 0 or false if it is of type boolean. • When initializing array, you must explicitly initialize all array element. mmouf@2018
  • 4. Single Dimension Array string[] books; //declare books = new string[3]; //create array of 3 element OR Books = new string[3] {"C#", "DotNet", "VB.Net"}; //create and init OR(Declare and create at 1 step) string[] books = {"C#", "DotNet", "VB.Net"}; //will set the array 3 OR(Declare and create at 1 step) string[] books = new string[3]{"C#", "DotNet", "VB.Net"}; mmouf@2018
  • 5. Two Dimension Array int[,] grid; grid = new int [2, 3]; grid[0, 0] = 5; grid[0, 1] = 4; grid[0, 2] = 3; grid[1, 0] = 2; grid[1, 1] = 1; grid[1, 2] = 2; Create and initialize: int[,] grid = {{5, 4, 3}, {2, 1, 0}}; OR int[,] grid = new int[2, 3]{{5, 4, 3}, {2, 1, 0}}; mmouf@2018
  • 6. Two Dimension Array Declaration is important in compilation. While creation is done at runtime So, you can make the size of array variable, which is very similar to Dynamic allocation. Example: int rows; int col; Console.WriteLine(“Enter number of rows”); rows = int.Parse(Console.ReadLine()); Console.WriteLine(“Enter number of columns”); col = int.Parse(Console.ReadLine()); int[,] ar; ar = new int[rows, col]; mmouf@2018
  • 7. Jagged Array C# also allows you to create a special type of two-dimensional array called a jagged array. A jagged array is an array of arrays in which the length of each array can differ. A jagged array can be used to create a table in which the lengths of the rows are not the same. Jagged arrays are declared by using sets of square brackets to indicate each dimension. For example, to declare a two-dimensional jagged array, you will use this general form: type[ ] [ ] array-name = new type[size][ ]; Here, size indicates the number of rows in the array. The rows, themselves, have not been allocated. Instead, the rows are allocated individually. This allows for the length of each row to vary. mmouf@2018
  • 8. Jagged Array Example: int[][] jagged = new int[3][]; jagged[0] = new int[4]; jagged[1] = new int[3]; jagged[2] = new int[5]; Once a jagged array has been created, an element is accessed by specifying each index within its own set of brackets. For example, to assign the value 10 to element 2, 1 of jagged, you would use this statement: jagged[2][1] = 10; mmouf@2018
  • 9. Properties of Array Length: returns number of element in the array. Example: int[] x; x = new int[7]; int y = x.Length; //y = 7 int[,] a; a = new int[3, 4]; int b = a.Length; //b = 12 (3*4) Rank: return the dimension of array Example: int z = x.Rank; //z = 1; int c = a.Rank; //c = 2; mmouf@2018
  • 10. Properties of Array Sort(): sort an array System.Array.Sort(array_name); //sort the array Clear(): set a range of elements in the array to zero, false or null reference System.Array.Clear(array_name, starting_index, numberofelement); Clone(): this method creates a new array instance whose elements are copies of the elements of the cloned array. int[] cl = (int[])data.Clone(); If the array being copied contains references to objects, the references will be copied and not the objects. Both arrays will refer to the same objects mmouf@2018
  • 11. Properties of Array GetLength(): this method returns the length of a dimension provided as an integer. Ex: int [,] data = {{0, 1, 2, 3}, {4, 5, 6, 7}}; int dim0 = data.GetLength(0); //2 int dim1 = data.GetLength(1); //4 IndexOf(): this method returns the integer index of the first occurrence of a value provided as argument or -1 if not found. (used in 1-dimension array) int[] data = {4, 6, 3, 8, 9, 3}; int Loc – System.Array.IndexOf(data, 9); //4 A method may return array: mmouf@2018
  • 12. Properties of Array The C# allows you to iterate over all items within a collection (ex: array,…) int []ar = new int[]{0, 1, 2, 3, 4, 5}; foreach(int I in ar) { Console.WriteLine(i); } You can’t modify the elements in a collection by using a foreach statement because the iteration variable is implicitly readonly. foreach(int i in ar) { i++ ; //compile time error Console.WriteLine(i); } mmouf@2018
  • 13. Implicitly Typed Local Variables and Arrays We can declare any local variable as var and the type will be inferred by the compiler from the expression on the right side of the initialization statement. This inferred type could be: Built-in type User-defined type Type defined in the .NET Framework class library Example: var int_variable = 6; // int_variable is compiled as an int var string_variable = “Aly"; // string_variable is compiled as a string var int_array = new[] { 0, 1, 2 }; // int_array is compiled as int[] var int_array = new[] { 1, 10, 100, 1000 }; // int[] var string_array = new[] { "hello", null, "world" }; // string[] mmouf@2018
  • 14. Implicitly Typed Local Variables and Arrays Notes: • var can only be used when you are to declare and initialize the local variable in the same statement. • The variable cannot be initialized to null. • var cannot be used on fields at class scope. • Variables declared by using var cannot be used in the initialization expression. In other words, var i = i++; produces a compile-time error. • Multiple implicitly-typed variables cannot be initialized in the same statement. • var can’t be used to define a return type • Implicit typed data is strongly typed data, variable can’t hold values of different types over its lifetime in a program mmouf@2018
  • 15. Classes Class is a named syntactic construct that describes common behavior and attribute. All classes are reference type and inherit from object class directly or indirectly. There is also: class variable( or static members). Ex: class MyClass { private int x; public int GetX() { return x; } } mmouf@2018
  • 16. Classes Each member in the class (class member or static member) must have an access modifier (public, private or protected) The class itself is a template, so to deal with the class we must have an object from this class. To have an object of a class: 1) Declaration : MyClass m; 2) Creation : m = new MyClass(); //Done at run time. Note: object of a class is a reference type. mmouf@2018
  • 17. Classes Passing Reference type variable to a function: Ex: class C1 { public int a; } class C2 { public void MyFunction(C1 x) { x.a = 20; } } mmouf@2018
  • 18. Classes class C3 { public static void Main() { C1 L; C2 M; L = new C1(); L.a = 5; M = new C2(); M.MyFunction(L); Console.WriteLine(L.a); // 20 } } With reference type variable: either call by value or call by reference it will be considered as a call by reference The this object is sent in calling the function of an object, it is the reference to the calling object. mmouf@2018
  • 19. Static Classes C# 2.0 added the ability to create static classes. There are two key features of a static class. First, no object of a static class can be created. Second, a static class must contain only static members. The main benefit of declaring a class static is that it enables the compiler to prevent any instances of that class from being created. Thus, the addition of static classes does not add any new functionality to C#. Within the class, all members must be explicitly specified as static. Making a class static does not automatically make its members static. mmouf@2018
  • 20. String Class 1) Insert: insert characters into string variable and return the new string Ex: String S = “C is great” S = S.Insert(2, “Sharp”); Console.WriteLine(S); //C Sharp is great 2) Length : return the length of a string. Ex : String msg = “Hello”; int slen = msg.Length; 3) Copy: creates new string by copying another string (static) Ex: String S1 = “Hello”; String S2 = String.Copy(S1); 4) Concat: Creates new string from one or more string (static) Ex: String S3 = String.Concat(“ä”, “b”, “c”, “d”); or use + operator S3 = “a” + “b” + “c” +”d”; mmouf@2018
  • 21. String Class 5) ToUpper, ToLower: return a string with characters converted upper or lower Ex: String sText = “Welcome”; Console.WriteLine(sText.ToUpper()); //WELCOME 6) Compare: compares 2 strings and return int.(static) -ve (first<second) 0 (first = second) +ve (first>second) Ex:String S1 = “Hello”; S2 = “Welcome”; int comp = String.Compare(S1, S2); //-ve there is another version of Compare that takes 3 parameters, the third is a boolean :true (ignore case) false (Check case) mmouf@2018