Value Types
Objectives • Discuss concept of value types – efficiency – memory management – value semantics – boxing – unboxing – simple types • Introduce struct value type – definition – use – advantages – limitations 2
Motivation • Programs make heavy use of some data objects – local variables, parameters, loop counters, etc. • Important that implementation be efficient – memory allocation – access – memory reclamation void Process() { for (int i = 0; i < 100000; i++) { ... would be expensive to allocate and reclaim Point p = new Point(); at each iteration ... } } 3
Runtime stack • Local variables and parameters stored on runtime stack – memory allocated and reclaimed automatically – efficient since memory management overhead is low stack parameter void Process(int x) { local int int y; local reference Stock s; Process x y ... s } ... 4
Managed heap • Reference type instances stored in managed heap – less efficient than stack due to overhead of heap management stack heap void Process(int x) { int y; reference type Stock s = new Stock(); Process x name y ... s price } shares ... 5
Value types • Value types contain data directly – not reference/object pair like reference types • All value types are derived from library ValueType class – many provided: int , char , TimeSpan , etc. – can define custom: struct , enum Object ValueType value types ... 6
Simple types • Simple types are library structures in the System namespace – can use structure name or C# alias Boolean bool Boolean char Char character sbyte SByte byte Byte short Int16 structure name Int32 i = 4; C# alias int j; ushort UInt16 integer int Int32 same type so j = i; can interoperate uint UInt32 long Int64 ulong UInt64 float Single floating point double Double decimal Decimal 7
Struct • Use struct to define custom value type – automatically derived from ValueType Object ValueType programmer struct defined struct 8
Struct abilities • struct has fields, constructors, properties, methods, etc. struct Point : IMeasureable { fields private int x, y; constructor public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } properties public int Y { get { return y; } set { y = value; } } method public void Scale(int a) { x *= a; y *= a; } public double Length() interface method { return Math.Sqrt(x * x + y * y); } } 9
Struct limitations • Struct has several limitations – does not support inheritance – cannot use variable initializers – cannot write custom default constructor – cannot define a destructor – constructors must explicitly initialize all fields error struct Point3D : Point { private int z = -1; error error ~Point3D() { ... } ... } 10
Value type local variable / parameter • Value type local variables and parameters stored on stack – efficient to allocate and reclaim memory stack void Process(Point p) parameter { Process local variable Point q = new Point(); ... p x } y q x y ... 11
Value type field • Reference type may have field of value type – field stored directly in containing object – reduces number of objects allocated in heap reference type class Rectangle { Point ll; value type fields stack heap Point ur; ... } ll x void Process() y Process { r Rectangle r = new Rectangle(); ur x y ... ... } 12
Value type array • Array of value types contains actual data – each element is default constructed – reduces number of object allocated in heap array of 5 Point s, Point[] polygon = new Point[5]; all default constructed x 0 x 0 x 0 x 0 x 0 polygon y 0 y 0 y 0 y 0 y 0 13
Default constructors • Value types all have default constructors that initialize fields – numeric types set to 0 – char set to null character – bool set to false – reference fields set to null • Programmer cannot code default constructor – always provided by compiler j 0 j set to 0 int j = new int(); p set to (0,0) Point p = new Point(); x 0 p y 0 14
Creation • Create value type instance implicitly or explicitly using new • Explicit creation recommended – invokes constructor so all fields will be initialized • Implicit creation does not invoke constructor – fields not initialized and must be assigned to before use void Process() x - p { y - implicit Point p; x 0 explicit q Point q = new Point(); y 0 } 15
Value semantics • Value types have value semantics – assignment – parameter passing – method return value – equality testing 16
Assignment • Assignment performs memberwise assignment – value of each field is copied Point p = new Point(3, 4); Point q = new Point(); assign q = p; x 3 x 3 q p y 4 y 4 17
Value parameter • Value type can be passed by value – memory allocated for parameter – field values copied – changes made in method affect only local copy value parameter void Process(Point q) x 3 q { y 4 ... } Point p = new Point(3, 4); x 3 p y 4 pass Process(p); 18
Reference parameter • Value type can be passed ref or out – no copy made – changes made in method affect actual parameter ref parameter void Process(ref Point q) { q.X = 5; changes p q.Y = 6; } p,q Point p = new Point(3, 4); x 5 y 6 pass Process(ref p); 19
Method return value • Value type returned from method by value – field values copied Point Add(Point a, Point b) { Point c = new Point(a.X + b.X, a.Y + b.Y); value copied return c; out of method } 20
Equality • Equals method used to compare value types – overridden in class ValueType to compare values – no need to override unless can implement more efficiently Point p = new Point(1, 2); Point q = new Point(1, 2); true, same data if (p.Equals(q)) ... class ValueType { public override bool Equals(object obj) { ... } ... } 21
Boxing • Value types are type compatible with object – value copied into wrapper automatically – called boxing • Boxing most useful for temporary storage – values often boxed and stored in data structure – later unboxed and used x 3 p y 4 Point p = new Point(3, 4); object o = p; boxed ... x 3 o y 4 22
Unboxing • Extract value type instance from box using cast – System.InvalidCastException thrown if cast fails x 3 o y 4 void Process(object o) { unbox Point q = (Point)o; ... } x 3 q y 4 23
Copy during boxing • Boxing copies value into new memory location – changes to original do not affect boxed copy x 3 Point p = new Point(3, 4); p y 5 value copied into box object o = p; modify original, p.y = 5; boxed copy x 3 o unchanged y 4 ... 24
Boxing efficiency • Boxing incurs runtime overhead – memory for wrapper allocated on managed heap – value copied into box – memory garbage collected after box no longer referenced Point p = new Point(3, 4); boxed object o = p; ... heap x 3 o y 4 25
Summary • Value types contain data directly – implemented efficiently – have value semantics • Value types interoperate with object – boxing occurs automatically – cast required for unboxing – use incurs some runtime overhead • Special category called simple value types – provide fundamental data types • Struct provides way to define structured value type 26
Recommend
More recommend