1. Trang chủ
  2. » Công Nghệ Thông Tin

Creating Value Types and Reference Types pdf

32 232 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

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 [...]... allocated to variables are of two types, value type and reference type Value types are the simplest types in C# Variables of value types directly contain their data in the variable Reference types variables contain only a reference to data The data is stored in a separate memory area A value type variable holds its value in the stack A reference type variable holds a reference to an object in the heap... Exercise 2 David is working on an application where he needs to accept the size of an array and its values He needs to identify the largest and smallest number in the array and based on that he needs to display the result NIIT Creating Values Types and Reference Types 5.31 5.32 Creating Values Types and Reference Types NIIT ... ) 5.28 Creating Values Types and Reference Types NIIT } Console.WriteLine ("arr[{0}] = {1}", i, String_Array[i]); } View the problem statement and answer the following question What is the output of the program? a str1 b str2 c Error message is displayed d arr[0] = str1 arr[1] = str2 5 NIIT The subscript number of an array starts from _ a 0 b -1 c 1 d 2 Creating Values Types and Reference Types 5.29... Collection classes, and they live in the System namespace ArrayList is useful when you want to manipulate the values in an array easily 5.30 Creating Values Types and Reference Types NIIT Exercises Exercise 1 David is working on a project where he needs to accept the total number of array elements and values from the user He also needs to arrange the array elements in ascending order, and display the result... 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 5.16 Creating Values Types and Reference Types NIIT 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 NIIT Creating Values Types. .. figure HEAP STACK Array @ 9 7 3 2 int [] array= {9, 7, 3, 2}; Value Stored in an int Array 5.24 Creating Values Types and Reference Types NIIT 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... 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 NIIT Creating Values Types and Reference Types 5.25 The following are the various classes of the System.Collection namespace Class... 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... limitations are: To resize an array, you have to create a new array, copy the elements into the new array, and then rearrange the array references To remove an element from an array, you need to create a copy of the element and then shift all the remaining elements up 5.26 Creating Values Types and Reference Types NIIT To add an element in between an array, you have to shift an element down by one place to... 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 NIIT Creating Values Types and Reference Types 5.23 Using Collections Arrays are useful, but they have their own limitations . 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. 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. 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

Ngày đăng: 01/08/2014, 09:21

Xem thêm: Creating Value Types and Reference Types pdf

TỪ KHÓA LIÊN QUAN