Tải bản đầy đủ (.pdf) (32 trang)

Creating Value Types and Reference Types pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (972.03 KB, 32 trang )

Creating Value
Types and Reference
Types
Chapter 5
The 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
 Use structures
 Use enumerations
 Implement arrays
 Use collections
Objectives

¤NIIT Creating Values Types and Reference Types 5.3
The 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.
int Num1=50;


The preceding statement assigns a value to the int type variable Num1 and the value is
copied to memory.
Reference types, such as classes are handled differently by the compiler. When you
declare a class variable the compiler does not generate code that allocates a block of
memory to hold a class. Instead it allocates a piece of memory that can potentially hold
the reference to another block of memory containing the class. The memory for the class
object is allocated when the new keyword is used to create an object.
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
int Num1;
Num1=50;
int Num2;

Num2=Num1;
Num1
Num2
50
50
5.4 Creating Values Types and Reference Types ¤NIIT
N
ote
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
both
Ford and Mercedes will refer to the same object.
The following code is an example of reference type variables:
using System;
namespace Ref_Type
{
class class1
{
static void Main (string[] args)
{
Car Ford = new Car ();
Ford.Model = 10;
Car Mercedes = Ford;
Mercedes.Display_Model ();
Ford.Display_Model ();
}
}

class Car
{
public int Model;
public void Display_Model ()
{
Console.WriteLine (Model);
}
}
}
¤NIIT Creating Values Types and Reference Types 5.5
N
ote
N
ote
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();
Ford.Model=10;
Car Mercedes;
Mercedes=Ford;
Ford

Mercedes
***
***
10
5.6 Creating Values Types and Reference Types ¤NIIT
A 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
struct
keyword.
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:
using System;
namespace Bills

{
public struct Bill_Details
{
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;
};
class TestStructure
{
public static void Main(string[] args)
{
Bill_Details billObj = new Bill_Details();
billObj.inv_No = "A101";
billObj.ord_Dt = "10/10/06";
billObj.custName = "Joe";
billObj.product = "Petrol";
billObj.cost = 100;
Using Structures
¤NIIT Creating Values Types and Reference Types 5.7
billObj.advance_Amt = 50;
billObj.due_Amt = 50;
Console.Clear();
Console.WriteLine("Invoice Number is {0}",
billObj.inv_No);
Console.WriteLine("Order Date is {0}",
billObj.ord_Dt);

Console.WriteLine("Customer Name is {0}",
billObj.custName);
Console.WriteLine("Product is {0}",
billObj.product);
Console.WriteLine("Cost is {0}",
billObj.cost);
Console.WriteLine("Advance Amount is {0}",
billObj.advance_Amt);
Console.WriteLine("Due Amount is {0}",
billObj.due_Amt);
Console.Read();
}
}
}
The output of the preceding code is as follows.
Output of the Bill Details Program
5.8 Creating Values Types and Reference Types ¤NIIT
Enumeration 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:
using System;
namespace EnumDays
{
class EnumTest
{
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;
Console.WriteLine("Sat = {0}", First_Day);
Console.WriteLine("Fri = {0}", Last_Day);
Console.ReadLine();

}
}
}
Declaring an Enumeration
Implementing Enumerations
Using Enumerations
¤NIIT Creating Values Types and Reference Types 5.9
In 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 enum
and displays the value Sat and Sun as an output.
The output of the preceding code is as follows.
Output of the Enumeration Days
5.10 Creating Values Types and Reference Types ¤NIIT
An 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:
int[] Score;
Declaring an Arra
y
Implementing Arrays
Arra
y
Name
Index

Value 0
Inde
x
Value 6
¤NIIT Creating Values Types and Reference Types 5.11
Declaring 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
5.12 Creating Values Types and Reference Types ¤NIIT
In 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
using System;
namespace ManipulateArray
{
class Palindrome
{
static void Main(string[] args)

{
char[] Str = new char[10];
//Enter a palindrome string
Console.WriteLine("Enter a Palindrome string
(Max 10 Char):");
//Accepting a string and converting in to Char array
Str=Console.ReadLine().ToCharArray();
//Calling the CheckPalidrome method
Console.WriteLine(CheckPalindrome(Str));
Console.ReadLine();
}
private static bool CheckPalindrome(char[] myString)
{
int startChar;
int lastChar;
startChar = 0;
//using Length method to calculate the total characters
in the array
Manipulating Array Elements
¤NIIT Creating Values Types and Reference Types 5.13
lastChar = myString.Length - 1;
//Executing the loop till the last character in the array
while (startChar < lastChar)
{
//Checking if the arrays from both the ends are equal
if (myString[startChar] == myString[lastChar])
{
startChar++;
lastChar ;
}

else
{
return false;
}
}
return true;
}
}
}
In the preceding example, a character array is declared and initialized. The value in the
array is entered by the user, which is expected to be a palindrome.
Length() method is
used to calculate the length of the array
myString and stored in a variable named
lastChar. 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
5.14 Creating Values Types and Reference Types ¤NIIT
{
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)
{
Console.Write("{0} \t",K);
}
Console.ReadLine();
}
}
}
The output of the preceding code is as follows.
Output of the forea ch Statement Usage in the Array
Similar to other data types, you can also pass arrays as parameter to a method.
Param Arrays
While declaring a method if you are not sure about the number of arguments passed as a
parameter, you can use the

param array.
The following code is an example of using the
param array in the methods parameter list:
using System;
namespace ParamArrays
{
public class ParamExample
¤NIIT Creating Values Types and Reference Types 5.15
N
ote
{
public int Adding_ArrayElement(params int[] List)
{
int Total = 0;
foreach ( int I in List )
{
Total += I;
}
return Total;
}
}
class Tester
{
static void Main(string[] args)
{
ParamExample 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.
5.16 Creating Values Types and Reference Types ¤NIIT
Problem 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

¤NIIT Creating Values Types and Reference Types 5.17
5. 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.
5.18 Creating Values Types and Reference Types ¤NIIT
N
ote
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.
¤NIIT Creating Values Types and Reference Types 5.19
9. 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:
using System;
namespace MatrixSubtractionApp
{
class MatrixSubtraction
{
public void subtract()
{
int[] Array1;

int[] Array2;
int[] Array3;
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++)
5.20 Creating Values Types and Reference Types ¤NIIT
{
Console.Write("{0}\t",Array1[i]);
}
Console.WriteLine("\n The Contents of Array 2 is:");
for (int i = 0; i < 3; i++)
{
Console.Write("{0} \t",Array2[i]);
}
//Subtraction of Array
for (int i = 0; i < 3; i++)
{
Array3[i] = Array1[i] - Array2[i];
}
//Display the Contents of Final Array
Console.WriteLine("\n The Result of Array Subtraction
is:");
for (int i = 0; i < 3; i++)
{
Console.Write("{0} \t",Array3[i]);
}
}
static void Main(string[] args)

{
MatrixSubtraction obj = new MatrixSubtraction();
obj.subtract();
Console.ReadLine();
}
}
}
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.
¤NIIT Creating Values Types and Reference Types 5.21
The 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
Multidimensional Arra
y
s
int [] Num; int[,] Num;
0
0 1 2 3 4 1
0 1 2 3 4
5.22 Creating Values Types and Reference Types ¤NIIT
The following code is an example of a multidimensional array:

using System;
using System.Collections.Generic;
using System.Text;
namespace MultiDimArray
{
class MultiArrayExample
{
static void Main(string[] args)
{
int sum=0;
int rowSum;
int[,] mArray = new int[2, 4]{
{2,2,2,2},
{3,3,3,3},
};
for (int row=0; row < 2; row++)
{
rowSum = 0;
for (int col=0; col < 4; col++)
{
Console.Write("{0}\t",mArray[row,col]);
rowSum=rowSum+mArray[row, col];

}
sum = sum + rowSum;
Console.Write(" = {0}", rowSum);
Console.WriteLine();

}
Console.WriteLine("The sum of the array is:{0}", sum);

Console.ReadLine();
}
}
}
The Array Class
The Array class is the base class for all the arrays in C#. The Array class is defined in
the
System namespace. The Array class provides properties and methods to work with
arrays.
¤NIIT Creating Values Types and Reference Types 5.23
Properties
The following table explains some of the most commonly used properties of the
Array
class.
Properties Explanation
Length Returns the total number of items in all the dimensions of an
array
Rank Returns the rank( number of dimensions) of an array
IsFixedSize Return a value indicating if an array has a fixed size or not
IsReadOnly Returns a value indicating if an array is read-only or not
Commonly Used Array Class Properties
Methods
The following table explains some of the most commonly used methods of the
Array
class.
Properties Explanation
Sort Performs sort operation on an array passed to it as a parameter
Clear Removes all items of an array and sets a range of items in the
array to 0
GetLength Returns the number of items in an Array

GetValue Returns the value of the specified item in an Array
IndexOf Returns the index of the first occurrence of a value in a
one-dimensional Array or in a portion of the Array
Commonly Used Array Class Methods
5.24 Creating Values Types and Reference Types ¤NIIT
Arrays are useful, but they have their own limitations. Arrays are used to collect the
elements of same data type. The .NET Framework provides several classes that also
collect elements in specialized ways. These classes are the Collection classes, and are
declared in the
System.Collections namespace and sub-namespaces.
The collection classes accept, hold, and return their elements as items. The element type
of a collection class is an object. To understand this, contrast an array of
int variables
(
int as a value type) with an array of objects (object is a reference type). int is a value
type, and an array of
int variables holds its int values directly, as shown in the following
figure.
Value Stored in an int Array
STACK
HEAP
9
7 3 2
Array
@
int [] array= {9, 7, 3, 2};
Using Collections
¤NIIT Creating Values Types and Reference Types 5.25
In the preceding figure, consider the effect when the array is an array of objects. You can
still add integer values to this array. The

int data type which is value type is
automatically converted to reference type. This action is called boxing, as shown in the
following figure.
Boxing
The element type of a collection class is an object. This means when you insert a value in
to a collection, it is always boxed. When you remove the value from the collection, you
must unbox it by using a cast. Unboxing means converting from reference type to value
type.
STACK
HEAP
@ @
@
@
Array
@
int [] array= {9, 7, 3, 2};
7
2
3
9

×