Value type variables contain data, whereas reference type variables hold the reference to the memory location where data is stored.. The following code is an example of value type variab
Trang 1The variables in a program are allocated memory at
run time in the system In C#, variables are referred
in two ways, value type and reference type Value
type variables contain data, whereas reference type
variables hold the reference to the memory location
where data is stored
This chapter explains how C# manages memory for
its data type variables It also explains the
implementation of value types such as structure and
enumeration This chapter describes how to
implement reference types such as arrays and
collections in C#
In this chapter, you will learn to:
Describe memory allocation
Trang 3The memory allocated to variables is referred to in two ways, value types and reference types All the built-in data types such as int,char, and float are value types When you declare an int variable, the compiler generates code that allocates a block of memory to hold an integer
Value type contains data Reference types contain address referring to a block of memory Value types are also called direct types because they contain data Reference types are also called indirect types because they hold the reference to the location where data is stored
To understand value type referencing, consider a scenario, where you declare a variable named Num1 as an int and assign the value 50 to it If you declare another variable Num2
as an int, and assign Num1 to Num2,Num2 will contain the same value as Num1 However, both the variables contain different copies of the value 50 If you modify the value in Num1, the value in Num2 does not change The following code is an example of value type variables:
int Num1=50; // declare and initialize Num1
int Num2=Num1; // Num2 contains the copy of the data in Num1 Num1++; // incrementing Num1 will have no effect on Num2 The following figure is a diagrammatic representation of the memory allocated to the value type variable
Memory Allocated for Value Type Variable
Describing Memory Allocation
Trang 4Note
All value types are created on the stack Stack memory is organized like a stack of
books piled on a rack
To understand reference types, consider a class named Car The object Mercedes of the class Car is initialized with Ford, which is also an object of the same class In this case bothFord and Mercedes will refer to the same object
The following code is an example of reference type variables:
public int Model;
public void Display_Model ()
Trang 5Note
Note
The following figure is a diagrammatic representation of the memory allocated to the reference type variable
Memory Allocated for the Reference Type Variable
All reference types are created on the heap Heap memory is like books arranged next to
each other in rows.
We have discussed int as a value type in the preceding examples, which is a built-in data type There are more value types like, structures and enumerations, which are
user-defined data types We also discussed class as reference type There are more examples of reference types like arrays and collections
Car Ford= new Car();
Trang 6A structure is a value type data type When you want a single variable to hold related data
of various data types, you can create a structure To create a structure you use the structkeyword
For example, if you want to maintain bill details, such as inv_No,ord_Dt, custName, product, cost, and due_Amt, in a single variable, you can declare a structure The
following code shows the syntax of a structure data type:
struct Bill_Details
{ public string inv_No; // Invoice Number
public string ord_Dt; // Order Date
public string custName; // Customer name
public string product; // Product Name
public double cost; // Cost of the product
public double due_Amt; // Total amount due
}
Like classes, structures contain data members which are defined within the declaration of the structure However, structures differ from classes and the differences are:
Structures are value types and they get stored in a stack
Structures do not support inheritance
Structures cannot have default constructor
The following program uses the Bill_Details structure:
public string inv_No;
public string ord_Dt;
public string custName;
public string product;
public double cost;
public double advance_Amt;
public double due_Amt;
Trang 7The output of the preceding code is as follows
Output of the Bill Details Program
Trang 8Enumeration is a value type data type, which means that enumeration contains its own values and cannot inherit or cannot pass inheritance Enumerator allows you to assign symbolic names to integral constants For example, you may want to write a program to represent the weekdays in a program You could use the integers 0, 1, 2, and 3 to
represent Saturday, Sunday, Monday, and Tuesday, respectively This representation would work, but it has a problem It is not convenient If the integer value 0 is used in code, it would not be obvious that 0 represents Saturday or Sunday To overcome such a problem, you can use enumeration To enumerate, you can use the enum keyword
To declare an enumeration type called Days, where the values are restricted to the
symbolic names of the weekdays, use the following code:
enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };
The names of days must appear within braces and must be separated by commas The enumeration type associates a numeric value with every element By default, the sequence
of values starts from 0 for the first element and goes forward by incrementing 1 each time
After declaring the enumeration type, you can use the enumeration type in the same manner as any other data type, as shown in the following code:
enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };
static void Main(string[] args)
{
int First_Day = (int)Days.Sat;
int Last_Day = (int)Days.Fri;
Trang 9In the preceding code, the enum has been declared as Days This enum has symbolic names, which appear within braces In the class EnumTest, Main() function displays the values of enum Days The local variable First_Day and Last_Day holds the value of enumand displays the value Sat and Sun as an output
The output of the preceding code is as follows
Output of the Enumeration Days
Trang 10An array is a collection of values of the same data type For example, you can create an
array that stores 10 integer type values The variables in an array are called the array elements Array elements are accessed using a single name and an index number
representing the position of the element within the array Array is a reference type data type The following figure shows the array structure in the system’s memory
Array Structure
An array needs to be declared before it can be used in a program You can declare an array by using the following statement:
datatype[] Arrayname;
The explanation of the elements of the preceding statement is as follows:
Datatype: Is used to specify the data type for the elements, which will be stored in
the array
[ ]: Is used to specify the rank of the array Rank is used to specify the size of the
array
Arrayname: Is used to specify the name of the array using which the elements of the
array will be initialized and manipulated
The following is an example of the array declaration:
Trang 11Declaring an array variable does not initialize the array in the memory When the array variable is initialized, you can assign values to the array elements
Initializing Array
Array is a reference type, therefore you need to use the new keyword to create an instance
of the array You must have noticed that while declaring the array, the size of the array was not mentioned The size of the array is specified while it is initialized The following statement is an example of array initialization:
int[] Score; // Array declaration
Score = new int[10]; //Array Instance
The preceding two statements can be combined into a single statement, and written, as follows:
int[] Score = new int[10];
In C#, the array subscript always starts with zero Therefore, the preceding statement creates an array of integers containing 10 elements, from 0 to 9
Assigning Values to the Array
You can assign values to each element of the array by using the index number, which is also called the array subscript of the element For example, to assign the value 5 to the first element of the array, you can use the following code:
int[] Score = new int[9];
Score[0] = 5;
You can also assign values to the array at the time of declaration However, in case of such explicit initialization, you cannot specify the size of the array, as shown in the following example:
int[] Score = {5, 10, 15};
The C# compiler implicitly initializes each array element to a default value depending on the array type For example, integer array would be initialized by 0 implicitly by the compiler
You can also create and initialize an integer array containing 10 elements, as shown in the following code snippet:
int[] Score = new int[10] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Initializing and Assigning Values to Array
Trang 12In the preceding statement, the curly braces ({}) are used to initialize the array elements
In the preceding statement, if you declare the array, you can omit the size of the array This is shown in the following statement:
int[] Score = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Copying an Array
When you copy the array variable, both the source and target variable refer to the same array instance in the memory To copy the array variable, you can use the following code snippet:
int[] Source = new int[10] {0, 1, 2, 3, 4};
int[] Target= Source;
In the preceding example, two array variables Source and Target are created, which point to the same instance in the memory
When an array is initialized, you can access the element values and manipulate them The following code is an example of array manipulation:
//Code to check a palindrome character array
char[] Str = new char[10];
//Enter a palindrome string
Console.WriteLine("Enter a Palindrome string
Trang 13lastChar While storing the length, the value is decreased by 1 because the subscript index number of the array starts with 0 The While loop is used to repeat the statements for comparing the characters in the array == operator is used to check for the equality of characters in the array
Many other loops are used for manipulating arrays The foreach loop is however
specifically used for manipulating arrays
foreach Usage
A statement that iterates through an array and executes the same set of instructions on each element is very common You can use any looping construct to iterate through an array, but the foreach statement interprets the common looping process by removing the need for you to check the array size
The following is the syntax of the foreach statement:
foreach(type identifier in expression)
statement-block
The following code has a set of instructions to declare an array called Numbers, process an array with the foreach statement, and write the values to the console, one line at a time: using System;
namespace ForEach
{
class ForEachExample
Trang 14{
static void Main (string[] args)
{
int [] Numbers = { 4, 3, 2, 1, 0, -1, -2, 9, 5 };
Console.WriteLine("The Contents of an Array is :");
foreach (int K in Numbers)
The output of the preceding code is as follows
Output of the foreach Statement Usage in the Array
Similar to other data types, you can also pass arrays as parameter to a method
Trang 15ParamExample Param_Exam = new ParamExample();
int Total = Param_Exam.Adding_ArrayElement(1,2,3,4,5,6,7);
Console.WriteLine( "The Result is {0}",Total );
Console.ReadLine();
}
}
}
The output of the preceding code is as follows
Output of the param Array
In the parameter list of a method, param array should be the last parameter
Trang 16Problem Statement
David, a student of California University, is currently pursuing B.Sc(IT) He is working
on a project named Matrix Subtraction He needs to perform the following tasks for his project:
Accept data in two Arrays
Perform the subtraction operation
Verify the value of subtraction
Help David to create the C# program using Visual Studio IDE
Solution
To solve the preceding problem, David needs to perform the following tasks:
1 Create a console-based application for Matrix Subtraction
2 Build and execute an application
Task 1: Creating a Console-Based Application for Matrix Subtraction
To create a console-based application for Matrix Subtraction, David needs to perform the following steps:
1 Select StartÆAll ProgramsÆMicrosoft Visual Studio 2005ÆMicrosoft Visual
Studio 2005 The Start Page - Microsoft Visual Studio window will be displayed
2 Select FileÆNewÆProject The New Project dialog box will be displayed
3 Select the project type as Visual C# from the Project types pane and
Console Application from the Templates pane
4 Type the name of the new project as MatrixSubtractionApp in the Name
text box
Activity: Matrix Subtraction Using Arrays
Trang 175 Specify the location where the new project is to be created as
c:\chapter5\Activity in the Location combo box, as shown in the following
figure
New Project Window
6 Click the OK button
Trang 18Note
7 Open the Solution Explorer window and right-click the Program.cs file
The shortcut menu is displayed, as shown in the following figure
Solution Explorer Window
8 Select the Rename option and type the new name as MatrixSubtraction.cs.
While renaming the Program.cs file, the Microsoft Visual Studio message box “You are renaming a file Would you also like to perform a rename in this project of all
references to the code element ‘Program’?” might appear Click the Yes button to
proceed
Trang 199 Double-click the MatrixSubtraction.cs file in the Solution Explorer
window The code view of the MatrixSubtraction.cs file is displayed
Code View of MatrixSubtraction.cs
10 Replace the existing code with the following code:
Array1 = new int[3] { 2, 3, 4 };
Array2 = new int[3] { 1, 2, 3 };
Array3 = new int[3];
Console.WriteLine("The Contents of Array 1 is :"); for (int i = 0; i < 3; i++)
Trang 20//Display the Contents of Final Array
Console.WriteLine("\n The Result of Array Subtraction is:");
for (int i = 0; i < 3; i++)
Task 2: Building and Executing an Application
To build and execute the application, David needs to perform the following steps:
1 Select BuildÆBuild Solution or press F6 to build the solution
2 Select DebugÆStart Debugging or press F5 to execute the application
3 Verify the output of the application
Trang 21The following window verifies the output of the executed program
Output of the MatrixSubtraction Application
The rank value of the array is also known as the dimension of the array The arrays declared and used in the preceding examples are the single dimensional arrays In single dimensional array, values are stored in a row You can also declare a multidimensional array, which stores data using a different dimension The following figure is a graphical representation of a single dimensional array and a multidimensional array
Single and Multidimensional Array