Value Types and Reference Types

   


Structs are value types, so when a struct object is assigned to a variable, the whole value is assigned, as opposed to reference-based values where only the reference is passed along. This can often lead to significantly different behavior between reference and value types.

Note

graphics/common.gif

It is generally more efficient to pass class instances around in a program than struct-based values because the former only involves a simple reference whereas the latter involves the whole value.


Consider, for example, the method called UpdateTime defined in lines 37 42 of Listing 18.4. It has one formal parameter of type TimeSpan. When we pass a TimeSpan argument to this type, the timeUpdate parameter is not assigned a copy of a reference as would have been the case with a class object, but is assigned a copy of the full value of the argument instead. So myTime (line 32) is totally independent from timeUpdate in line 37 (had they been reference-based, they would both have referenced the same object). This is confirmed by the sample output where myTime clearly is not affected by the update that is taking place in line 39.

Listing 18.4 TimeSpanMethod.cs
01: using System; 02: 03: public struct TimeSpan 04: { 05:     private uint totalSeconds; 06: 07:     public TimeSpan(uint initialTotalSeconds) 08:     { 09:         totalSeconds = initialTotalSeconds; 10:     } 11: 12:     public uint Seconds 13:     { 14:         get 15:         { 16:             return totalSeconds; 17:         } 18: 19:         set 20:         { 21:             totalSeconds = value; 22:         } 23:     } 24: } 25: 26: class Tester 27: { 28:     public static void Main() 29:     { 30:         TimeSpan myTime = new TimeSpan(480); 31: 32:         UpdateTime(myTime); 33:         Console.WriteLine("Time outside UpdateTime method: {0} ", 34:             myTime.Seconds); 35:     } 36: 37:     public static void UpdateTime(TimeSpan timeUpdate) 38:     { 39:         timeUpdate.Seconds = timeUpdate.Seconds + 50; 40:         Console.WriteLine("Time inside UpdateTime method: {0} ", 41:             timeUpdate.Seconds); 42:     } 43: } Time inside UpdateTime method: 530 Time outside UpdateTime method: 480 

   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net