Intro To C# - Part 2
Intro To C# - Part 2
Kitaw A.
Arrays
An array stores a fixed-size sequential collection of elements of
the same type
An array is used to store a collection of data
We can think of an array as a collection of variables of the same
type stored at contiguous memory locations
Arrays
Declaring Arrays
Arrays are declared in the following way:
<baseType>[] <name>;
Here, <baseType> may be any variable type
E.g.
int[] array;
Arrays
Arrays must be initialized array
before we have access to them E.g.
Arrays can be initialized in int[] array={3,5,8,3};
two ways
Or
We can either specify the
contents of the array in a literal int[] array=new int[4];
form, or we can specify the array[0]=3;
size of the array and use the array[1]=5;
new keyword to initialize the array[2]=8;
array[3]=3;
Arrays
The foreach loop
The foreach loop repeats a group of embedded statements for each
element in an array.
foreach(<type> <identifier> in <list>) {
statement(s);
}
foreach(int x in array){
Console.WriteLine(x);
}
Arrays
Multi-dimensional Arrays
C# allows multidimensional arrays
Multidimensional arrays come in two varieties: rectangular and
jagged
Rectangular arrays represent an n-dimensional block of memory,
and jagged arrays are arrays of arrays.
Arrays
Rectangular arrays
Rectangular arrays are declared using commas to separate each dimension
The following declares a rectangular two-dimensional array, where the
dimensions are 3 by 3:
int[,] matrix = new int[2,3];
The GetLength method of an array returns the length for a given dimension
(starting at 0):
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
matrix[i,j] = i * 3 + j;
Arrays
Rectangular arrays
A rectangular array can be initialized as follows (to create an array
identical to the previous example):
int[,] matrix =
{
{0,1,2},
{3,4,5}
}
Arrays
Jagged arrays
Jagged arrays are declared using successive square brackets to
represent each dimension.
Here is an example of declaring a jagged two-dimensional array,
where the outermost dimension is 2:
int[][] matrix = new int[2][];
Arrays
Jagged arrays
The inner dimensions aren’t specified in the declaration because,
unlike a rectangular array, each inner array can be an arbitrary
length. for (int i = 0; i < matrix.GetLength(0); i++)
{
matrix[i] = new int[3];
for (int j = 0; j < matrix[i].Length; j++)
matrix[i][j] = i * 3 + j;
}
Arrays
The Array class
The Array class is the base class for all the arrays in C#
It is defined in the System namespace
The Array class provides various properties and methods to work with
arrays
Arrays
The Array class
Strings
In C#, you can use strings as array of characters
However, more common practice is to use the string keyword to
declare a string variable
The string keyword is an alias for the System.String class.
Strings
Creating a String Object
You can create string object using one of the following methods:
By assigning a string literal to a String variable
string country=”Ethiopia”;
By using a String class constructor
char[] letters={‘C’,’-’,’s’,’h’,’a’,’r’,’p’};
string lan=new String(letters);
Strings
Creating a String Object
By using the string concatenation operator (+)
string givenName=”Anders”;
string sureName=”Hejlsberg”;
string fullName=givenName+” “+sureName;
By retrieving a property or calling a method that returns a string
string givenName=”Anders”;
string givenNameUpper=givenName.ToUpper();
Strings
The String class
The String class define a number of properties and methods that
can be used to manipulate strings
The Length property gets the number of characters in the current
String object
Strings
The String class
Functions
Functions, also called methods, in C# are a means of providing
blocks of code that can be executed at any point in an application
For example, we could have a function that calculates the
maximum value in an array
We can use this function from any point in our code, and use the
same lines of code in each case
This function can be thought of as containing reusable code
Functions
E.g.
int GetMax(int[] a){
int max=a[0];
for(int i=1;i<a.Length;i++){
max=(a[i]>max)?a[i]:max;
}
return max;
}
Functions
Defining a function
<access specifier> <return type> method_name(parameter_list)
{
// method body
}
Functions
Access specifier: determines visibility of the method/function
from another class
The following access modifiers can be used in C#:
public: accessible to all other functions and objects
private: function can only be accessed with in the defining class
protected: accessible to child classes
internal: accessible for all classes with in the same project
Functions
Return type: A function may return a value. The return type is the data type
of the value the function returns. If the function is not returning any values,
then the return type is void
Method name: Method name is a unique identifier
Parameter list: Enclosed between parentheses, the parameters are used to
pass and receive data from a method. The parameter list refers to the type,
order, and number of the parameters of a method. Parameters are optional;
that is, a method may contain no parameters
Method body: This contains the set of instructions needed to complete the
required activity
Functions
E.g.
public int FindMax(ref int num1, ref int num2){
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Functions
Parameter Arrays
C# allows us to specify one (and only one) special parameter for a function
This parameter, which must be the last parameter in the function definition,
is known as a parameter array
Parameter arrays allow us to call functions using a variable amount of
parameters, and are defined using the params keyword.
Parameter arrays allow us to pass several parameters of the same type that
are placed in an array that we can use from within our function
Functions
Parameter Arrays
<returnType> <functionName>(<p1Type> <p1Name>, ... ,
params <type>[] <name>)
{
...
return <returnValue>;
}
We can call this function using code like:
<functionName>(<p1>, ... , <val1>, <val2>, ...)
Here <val1>, <val2>, and so on are values of type <type> that are used to
initialize the <name> array.
Functions
Parameter Arrays
int GetSum(params int[] a){
int sum = 0;
foreach(int n in a)
sum+=n;
return sum;
}
The following are all valid calls to the above function:
GetSum(2,3);
GetSum(1,2,3,4,5);
GetSum(1);
GetSum();
Functions
Passing Parameters to a Function
When function with parameters is called, you need to pass the parameters to
the function
There are three ways that parameters can be passed to a function:
Functions
Passing Parameters to a Function
Parameter modifiers are used to control how parameters are passed
Parameter modifier Passed by Variable must be assigned