Learning Objectives
After completing this session, you will be able to: Define Arrays and its types
Explain Methods and how to call C# methods
Identify Parameters and different ways of passing parameters Describe the overview of method overloading
Arrays
An array is an indexed collection of objects, all of the same type. C# arrays are somewhat different from arrays in C++ and other languages—because they are objects. This provides them with built- in support like useful methods and properties. There are three types of arrays:
One-dimensional arrays
Multidimensional arrays rectangular arrays, Multidimensional jagged arrays
Declaring an array:
C# provides native syntax for the declaration of Array objects: int[] myIntArray;
What is actually created, however, is an object of type System.Array. Arrays in C# thus provide you with the best of both worlds: easy-to-use C-style syntax underpinned with an actual class definition so that instances of an array have access to the methods and properties of
System.Array.
Once an array is declared, it must also be instantiated using the new keyword. The following declaration sets aside memory for an array holding five integers:
int[] myIntArray = new int[5];
When an array is created for value types, each element initially contains the default value for the type stored in the array. In the earlier example, each of those array elements is initialized to 0, the default value for integer types. With an array of reference types, the elements are not initialized to their default values. Instead, they are initialized to null.
Arrays are zero-based, which means that the index of the first element is always zero — in this case, myArray[0].
As arrays are objects, they have properties. One of the more useful properties of the Array class is Length, which tells how many objects are in an array.
for (int i = 0;i<5;i++) {
empArray[i] = i; }
for (int i = 0;i<empArray.Length;i++) {
MessageBox.Show(empArray[i]); }
Initializing Array Elements:
Rather than assigning elements to the array as you have done so far, it is possible to initialize the contents of an array at the time it is instantiated by providing a list of values delimited by curly braces ({}). C# provides two different syntaxes to accomplish the same task:
int[] myIntArray = new int[5] { 2, 4, 6, 8, 10 };
int[] myIntArray = { 2, 4, 6, 8, 10 };
Multidimensional Rectangular Arrays:
A rectangular array is an array of two (or more) dimensions. In the classic two-dimensional array, the first dimension is the number of rows and the second dimension is the number of columns. To declare and instantiate a two-dimensional rectangular array named myRectangularArray that contains two rows and three columns of integers,
int [,] myRectangularArray = new int[2,3];
for (int i = 0;i < rows;i++) {
for (int j = 0;j<columns;j++) {
rectangularArray[i,j] = i+j; }
}
The brackets in the int[,] declaration indicate that the type is an array of integers, and the single comma indicates the array has two dimensions; two commas would indicate three dimensions, and so on. Just as you can initialize a one-dimensional array using bracketed lists of values, you can initialize a two-dimensional array using a similar syntax.
//this is a 4x3 array (four rows by three columns) int[,] rectangularArray =
{
{0,1,2}, {3,4,5}, {6,7,8}, {9,10,11} };
Multidimensional Jagged Arrays:
A jagged array is an array of arrays. Specifically, a jagged array is a type of multi-dimensional array in which each row can be a different size from all the other rows. You would declare a two- dimensional jagged array of integers named myJaggedArray as follows:
int [] [] myJaggedArray;
To access the fifth element of the third array: myJaggedArray[2][4]
Tip:
Notice that when you accessed the members of the rectangular array, you put the indexes all within one set of square brackets:
ArrayrectangularArray[row,column]
However, with a jagged array you need a pair of brackets: jaggedArray[row][column]
You can keep this straight by thinking of the first as a single array of more than one dimension and the jagged array as an array of arrays.
System.Array:
As you say C# implements arrays with the class System.Array. .NET Framework also provides a number of other built-in collection classes, including the ArrayList, Queue, and Stack. The usage of those depends on the requirement of the situation. These can be found in the System.Collections namespace.The following are the members of the Array Class.
Public Properties:
S.No. Name Description
1 IsFixedSize Gets a value indicating whether the Array has a fixed size. 2 IsReadOnly Gets a value indicating whether the Array is read-only.
3 IsSynchronized Gets a value indicating whether access to the Array is synchronized (thread safe).
4 Length Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.
5 LongLength Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.
6 Rank Gets the rank (number of dimensions) of the Array.
Public Properties:
S.No. Name Description
1 AsReadOnly Returns a read-only wrapper for the specified array.
2 BinarySearch Overloaded. Searches a one-dimensional sorted Array for a value, using a binary search algorithm.
3 Clear Sets a range of elements in the Array to zero, to false, or to a null reference (Nothing in Visual Basic), depending on the element type.
4 Clone Creates a shallow copy of the Array.
5 ConstrainedCopy Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. Guarantees that all changes are undone if the copy does not succeed completely.
6 ConvertAll Converts an array of one type to an array of another type. 7 Copy Overloaded. Copies a range of elements in one Array to another
Array and performs type casting and boxing as required. 8 CopyTo Overloaded. Copies all the elements of the current one-
dimensional Array to the specified one-dimensional Array. 9 CreateInstance Overloaded. Initializes a new instance of the Array class.
10 Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)
11 Exists Determines whether the specified array contains elements that match the conditions defined by the specified predicate.
12 Find Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Array.
13 FindAll Retrieves all the elements that match the conditions defined by the specified predicate.
14 FindIndex Overloaded.
15 FindLast Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire Array.
16 FindLastIndex Overloaded
17 ForEach Performs the specified action on each element of the specified array.
18 GetEnumerator Returns an IEnumerator for the Array.
19 GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)
20 GetLength Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)
S.No. Name Description
21 GetLongLenth Gets a 64-bit integer that represents the number of elements in the specified dimension of the Array.
22 GetLowerBound Gets the lower bound of the specified dimension in the Array. 23 GetType Gets the Type of the current instance. (Inherited from Object.) 24 GetUpperBound Gets the upper bound of the specified dimension in the Array. 25 GetValue Overloaded. Gets the value of the specified element in the current
Array.
26 IndexOf Overloaded. Returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the Array.
27 Intialize Initializes every element of the value-type Array by calling the default constructor of the value type.
28 LastIndexOf Overloaded. Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array.
29 ReferenceEquals Overloaded. Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array.
30 Resize Changes the size of an array to the specified new size. 31 Reverse Overloaded. Reverses the order of the elements in a one-
dimensional Array or in a portion of the Array.
32 SetValue Overloaded. Sets the specified element in the current Array to the specified value.
33 Sort Overloaded. Sorts the elements in one-dimensional Array objects. 34 ToString Returns a String that represents the current Object. (Inherited from
Object.)
35 TrueForAll Determines whether every element in the array matches the conditions defined by the specified predicate.
Protected Methods:
S.No. Name Description
1 Finalize Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
2 MemberwiseClone Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Methods
A method is a code block containing a series of statements. In C#, every executed instruction is done so in the context of a method.
Methods are declared within a class or struct by specifying the access level, the return value, the name of the method, and any method parameters. Method parameters are surrounded by
parentheses, and separated by commas. Empty parentheses indicate that the method requires no parameters.
This class contains three methods: class Motorcycle
{
public void StartEngine() { }
public void AddGas(int gallons) { }
public int Drive(int miles, int speed) { return 0; } }
Calling the Method:
Calling a method on an object is similar to accessing a field. After the object name, add a period, the name of the method, and parentheses. Arguments are listed within the parentheses, and separated by commas. The methods of the Motorcycle class can therefore be called like this: Motorcycle moto = new Motorcycle ();
moto.StartEngine(); moto.AddGas(15); moto.Drive(5,20);
As shown in the previous code snippet, passing arguments to a method is simply a matter of providing them in the parentheses when calling a method. To the method being called, the incoming arguments are called parameters.
The parameters a method receives are also provided in a set of parentheses, but the type and a name for each parameter must be specified. The name does not have to be the same as the argument.
Example:
public static void PassesInteger() {
int fortyFour = 44; TakesInteger(fortyFour); }
static void TakesInteger(int i) {
i = 33; }
Here a method called PassesInteger passes an argument to a method called TakesInteger. Within PassesInteger, the argument is named fortyFour, but in TakeInteger, this is a parameter named i. This parameter exists only within the TakesInteger method. Any number of other variables can be named i, and they can be of any type, so long as they are not parameters or variables declared inside this method.
Notice that TakesInteger assigns a new value to the provided argument. One might expect this change to be reflected in the PassesInteger method once TakeInteger returns, but in fact the value in the variable fortyFour remains unchanged. This is because int is a value type. By default, when a value type is passed to a method, a copy is passed instead of the object itself. As they are copies, any changes made to the parameter have no effect within the calling method. Value types get their name from the fact that a copy of the object is passed instead of the object itself. The value is passed, but not the same object.
Parameters
Parameters are means of passing values to a method. Overloading is the creation of more than one procedure, instance constructor, or property in a class with the same name but different argument types are params, ref, out.
Params: The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.
Example:
// cs_params.cs using System;
public class MyClass {
public static void UseParams(params int[] list) {
for (int i = 0 ; i < list.Length; i++) {
Console.WriteLine(list[i]); }
Console.WriteLine(); }
public static void UseParams2(params object[] list) {
for (int i = 0 ; i < list.Length; i++) {
Console.WriteLine(list[i]); }
Console.WriteLine(); }
static void Main() {
UseParams(1, 2, 3);
UseParams2(1, 'a', "test");
// An array of objects can also be passed, as long as // the array type matches the method being called. int[] myarray = new int[3] {10,11,12};
UseParams(myarray); }
}
ref:
The ref keyword causes arguments to be passed by reference. The effect is that any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword. For example:
class RefExample {
static void Method(ref int i) {
i = 44; }
static void Main() { int val = 0; Method(ref val); // val is now 44 } }
Out:
The out keyword causes arguments to be passed by reference. This is similar to the ref
keyword, except that ref requires that the variable be initialized before being passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.
Example:
class OutExample {
static void Method(out int i) {
i = 44; }
static void Main() { int value; Method(out value); // value is now 44 } } Method Overloading
Overloading is the creation of more than one procedure, instance constructor, or property in a class with the same name but different argument types.
Rules for Overloading:
You create an overloaded member for a class by adding two or more properties or methods with the same name. Except for overloaded derived members, each overloaded member must have different parameter lists, and the following items cannot be used as a differentiating feature when overloading a property or procedure:
Modifiers, such as ByVal or ByRef, that applies to a member or parameters of the member.
Names of parameters Return types of procedures
The following is an example for overloading: using System;
namespace overload {
class Program {
void add(int a, int b) {
int result; result=a+b;
Console.WriteLine("The sum of two integers is :" + result); }
void add(string a, string b) {
string result; result = a + b;
Console.WriteLine("The concatenation of two strings is :" + result);
}
static void Main(string[] args) {
Program obj = new Program(); obj.add(1, 2); obj.add("Hi ", "Yaso"); } } } Summary Arrays:
Single-dimensional array: It is the simplest form of arrays
Multidimensional array: It is an array with more than one dimension.
Jagged Array: They are often called array of arrays. An element of a jagged array itself is an array.
Mixed arrays: It is a combination of multi-dimension arrays and jagged arrays. Methods:
A method is a code block containing a series of statements.
Methods are declared by specifying the access level, the return value, the name of the method, and any method parameters.
Parameters: Parameters are means of passing values to a method. Different types of parameters are as follows:
Method Overloading: Method overloading is a way to have more than one method having the same name, but each method has a different signature.
Test your Understanding
1. What are the types of arrays?
2. What is jagged array and how do you declare it? 3. What is method and how do you define it? 4. What are the types of parameters?
5. State the difference between parameter and parameter value. 6. What do you mean by Method Overloading?