Data types in C# come in two basic varieties: value or reference types. A value type tends to be smaller and directly references its data, while a reference type tends to be larger and holds reference that indicates where the data is stored. As such a reference type is not so closely linked to its data and several refernces can indicate the same piece of data. Below, we have a program that demonstrates how each of these types works. The char[] is a reference type and both of the data types reference the same array of characters, as this program demonstrates.
using System; namespace XoaX { class Program { static void Main(string[] args) { // int is a value type int i = 9; int j = i; Console.WriteLine("i = " + i + " j = " + j); i = 12; Console.WriteLine("i = " + i + " j = " + j); Console.WriteLine(); // char[] is a reference type char[] caOldName = "Simon".ToCharArray(); char[] caNewName = caOldName; Console.Write("Old Name = "); Console.WriteLine(caOldName); Console.Write("New Name = "); Console.WriteLine(caNewName); // Changing the caNewName changes caOldName too! caNewName[0] = 'P'; caNewName[1] = 'e'; caNewName[2] = 't'; caNewName[3] = 'e'; caNewName[4] = 'r'; Console.Write("Old Name = "); Console.WriteLine(caOldName); Console.Write("New Name = "); Console.WriteLine(caNewName); Console.WriteLine(); } } }
i = 9 j = 9 i = 12 j = 9 Old Name = Simon New Name = Simon Old Name = Peter New Name = Peter Press any key to continue . . .
© 20072024 XoaX.net LLC. All rights reserved.