Download presentation
Presentation is loading. Please wait.
Published byNathan James Modified over 9 years ago
1
Common Type System.NET Types Hierarchy, Cloning, Comparing, Collection Iterators, Value and Reference Types Svetlin Nakov Technical Trainer www.nakov.com Software University http://softuni.bg
2
2 1.What is Common Type System (CTS)?1.What is Common Type System (CTS)? 2.The System.Object type2.The System.Object type 3.Operators and 3.Operators is and as 4.Object Cloning4.Object Cloning 5.The IComparable Interface5.The IComparable Interface 6.The IEnumerable interface6.The IEnumerable interface 7.Value Types and Reference Types7.Value Types and Reference Types 8.Passing Parameters: in, out, ref Table of Contents
3
What is Common Type System (CTS)?
4
4 Building blocks of.NET Framework Inside.NET Framework Operating System (OS) Common Language Runtime (CLR) Base Class Library (BCL) ADO.NET, EF, LINQ and XML (Data Tier) WCF and WWF (Communication and Workflow Tier) ASP.NET Web Forms, MVC, Web API, SignalR WindowsForms WPF / XAML WinJS / Win8 C#C++VB.NETJ#F#PHPPerl Delphi… FCL CLR
5
5 .NET Common Type System (CTS) Defines CLR supported Data types (e.g. Int32, String, dynamic ) Operations performed on them, e.g. +, -, [] Extends the compatibility between different.NET languages Supports two types of data Value types (values), e.g. 20, true, 'a' Reference types (pointers to the heap), e.g. strings and arrays All data types are inheritors of All data types are inheritors of System.Object What is CTS?What is CTS?
6
6.NET CTS Types Hierarchy.NET CTS Types Hierarchy Types (System.Object) Value Types (System.ValueType) Reference Types Primitive Value Types Structures Enumerable Types Self Descriptive Types Pointers ClassesArrays Boxed Value Types Interfaces User Defined Classes Delegates Dynamic
7
The System.Object TypeThe System.Object Type The Parent of All.NET Types
8
8 System.Object is the base class for each.NET type Inherited by default when a new type is defined Important virtual methods: Equals() – comparison with other object ToString() – represents the object as a string GetHashCode() – evaluates the hash code (used with hash-tables) In Java all objects inherit from java.lang.Object Value type do not inherit its, only classes / interfaces System.Object TypeSystem.Object Type
9
Overriding the Virtual Methods in System.Object
10
10 By default the operator == calls ReferenceEquals() Compares the addresses for reference types Or the binary representation for value types The methods Equals(), GetHashCode() should be defined at the same time (in C# and Java) The same applies for the operators == and != verride You can override Equals() and use it for == and != Overriding System.Object's Virtual MethodsOverriding System.Object's Virtual Methods
11
11 Overriding System.Object Methods – ExampleOverriding System.Object Methods – Example public class Student { public string Name { get; set; } public string Name { get; set; } public int Age { get; set; } public int Age { get; set; } public override bool Equals(object param) public override bool Equals(object param) { // If the cast is invalid, the result will be null // If the cast is invalid, the result will be null Student student = param as Student; Student student = param as Student; // Check if we have valid not null Student object // Check if we have valid not null Student object if (student == null) if (student == null) return false; return false; // Compare the reference type member fields // Compare the reference type member fields if (! Object.Equals(this.Name, student.Name)) if (! Object.Equals(this.Name, student.Name)) return false; return false; // Compare the value type member fields // Compare the value type member fields if (this.Age != student.Age) if (this.Age != student.Age) return false; return false; return true; return true; } // the example continues
12
12 Overriding System.Object Methods – Example (2)Overriding System.Object Methods – Example (2) public static bool operator == (Student student1, public static bool operator == (Student student1, Student student2) Student student2) { return Student.Equals(student1, student2); return Student.Equals(student1, student2); } public static bool operator != (Student student1, public static bool operator != (Student student1, Student student2) Student student2) { return !(Student.Equals(student1, student2)); return !(Student.Equals(student1, student2)); } public override int GetHashCode() public override int GetHashCode() { return Name.GetHashCode() ^ Age.GetHashCode(); return Name.GetHashCode() ^ Age.GetHashCode(); }}
13
13 Classes can override the virtual ToString() method toString() in Java and JavaScript, __toString() in PHP Overriding ToString() public class Student // C# class Student { public string Name { get; set; } public string Name { get; set; } public int Age { get; set; } public int Age { get; set; } public override ToString() public override ToString() { return "Student " + this.Name + ", age = " + this.Age; } { return "Student " + this.Name + ", age = " + this.Age; }} function Student(name, age) { // JavaScript class Student this.name = name; this.age = age; } this.name = name; this.age = age; } Student.prototype.toString = function() { return 'Student ' + this.name + ', age = ' + this.age; } return 'Student ' + this.name + ', age = ' + this.age; }
14
Overriding the Virtual Methods in System.Object Live Demo
15
15 The type has some other methods, which are inherited by all.NET types: The System.Object type has some other methods, which are inherited by all.NET types: GetType() Returns type's metadata as a Returns type's metadata as a System.Type MemberwiseClone() Copies the binary representation of the variable into a new variable (shallow clone) ReferenceEquals() Compares if two object have the same reference More About System.ObjectMore About System.Object
16
is and as Operators
17
17 The operator ( instanceof in Java and PHP) The is operator ( instanceof in Java and PHP) Checks if an object an is instance of given type Polymorphic operation 5 is Int32 5 is object 5 is IComparable 5 is IComparable The operator The as operator Casts a reference type to another reference type Returns value if it fails, e.g. if the types are incompatible Returns null value if it fails, e.g. if the types are incompatible Type Operators in C#Type Operators in C#
18
class Base { } class Derived : Base { } class TestOperatorsIsAndAs { static void Main() static void Main() { Object objBase = new Base(); Object objBase = new Base(); if (objBase is Base) if (objBase is Base) Console.WriteLine("objBase is Base"); Console.WriteLine("objBase is Base"); // Result: objBase is Base // Result: objBase is Base if (! (objBase is Derived)) if (! (objBase is Derived)) Console.WriteLine("objBase is not Derived"); Console.WriteLine("objBase is not Derived"); // Result : objBase is not Derived // Result : objBase is not Derived if (objBase is System.Object) if (objBase is System.Object) Console.WriteLine("objBase is System.Object"); Console.WriteLine("objBase is System.Object"); // Result : objBase is System.Object // Result : objBase is System.Object // the example continues 18 Operators is and as – ExampleOperators is and as – Example
19
19 Operators is and as – Example (2)Operators is and as – Example (2) Base b = objBase as Base; Base b = objBase as Base; Console.WriteLine("b = {0}", b); Console.WriteLine("b = {0}", b); // Result: b = Base // Result: b = Base Derived d = objBase as Derived; Derived d = objBase as Derived; if (d == null) if (d == null) Console.WriteLine("d is null"); Console.WriteLine("d is null"); // Result: d is null // Result: d is null Object o = objBase as Object; Object o = objBase as Object; Console.WriteLine("o = {0}", o); Console.WriteLine("o = {0}", o); // Result: o = Base // Result: o = Base Derived der = new Derived(); Derived der = new Derived(); Base bas = der as Base; Base bas = der as Base; Console.WriteLine("bas = {0}", bas); Console.WriteLine("bas = {0}", bas); // Result: bas = Derived // Result: bas = Derived }}
20
Operators is and as Live Demo
21
Object CloningObject Cloning
22
22 In programming cloning an object means to create an identical copy of certain object Shallow cloning (shallow copy) Uses the protected MemberwiseClone() method Copies the value types bit by bit (binary) Copies only the addresses of the reference types Deep cloning (deep copy) Recursively copies all member data Implemented manually by the programmer Object CloningObject Cloning
23
23 Types which allow cloning should implement the interface Types which allow cloning should implement the ICloneable interface Have copy constructor in C++ / implement Cloneable in Java The method of the The Clone() method of the ICloneable The only method of the interface Returns an identical copy of the object Returns object must be casted later You decide whether to create a deep or shallow copy or something mixed Object Cloning (2)Object Cloning (2)
24
class LinkedList : ICloneable { public T Value { get; set; } public T Value { get; set; } public LinkedList NextNode { get; private set; } public LinkedList NextNode { get; private set; } public LinkedList(T value, public LinkedList(T value, LinkedList nextNode = null) LinkedList nextNode = null) { this.Value = value; this.Value = value; this.NextNode = nextNode; this.NextNode = nextNode; } object ICloneable.Clone() // Implicit implementation object ICloneable.Clone() // Implicit implementation { return this.Clone(); return this.Clone(); } // the example continues 24 Object Cloning – ExampleObject Cloning – Example
25
25 Object Cloning – Example(2)Object Cloning – Example (2) public LinkedList Clone() // our method Clone() { // Copy the first element // Copy the first element LinkedList original = this; LinkedList original = this; T valueOriginal = original.Value; T valueOriginal = original.Value; LinkedList result = new LinkedList (valueOriginal); LinkedList result = new LinkedList (valueOriginal); LinkedList copy = result; LinkedList copy = result; original = original.NextNode; original = original.NextNode; // Copy the rest of the elements // Copy the rest of the elements while (original != null) while (original != null) { valueOriginal = original.Value; valueOriginal = original.Value; copy.NextNode = new LinkedList (valueOriginal); copy.NextNode = new LinkedList (valueOriginal); original = original.NextNode; original = original.NextNode; copy = copy.NextNode; copy = copy.NextNode; } return result; return result;}
26
Deep and Shallow Object CloningDeep and Shallow Object Cloning Live Demo
27
27 Cloning objects in JS: JSON serialization + deserialization Deep cloning in JavaScript: Arrays in PHP are copied by value (cloned by default): In PHP the keyword clone makes shallow object copy: Object Cloning in JavaScript and PHP var obj = { lang: "JS", point: { x: 20, y: -50 }, arr: [1.5, 3] } var clonedObj = JSON.parse(JSON.stringify(obj)); $arr = array("lang" => "PHP", "arr" => array(1.5, 3)); $arrCloned = $arr; $obj = new stdClass(); $obj->lang = "PHP"; $obj->arr = array(1, 2, 3); $clonedObj = clone $obj;
28
The IComparable InterfaceThe IComparable Interface Comparing Objects
29
29 The System.IComparable interface Implemented by the types, which can be compared (ordered in increasing order) Interface Comparable in Java The CompareTo(T) method should return: Number < 0 – if the passed object is bigger than this object Number = 0 – if the passed object is equal to this object Number > 0 – if the passed object is smaller than this object IComparable InterfaceIComparable Interface
30
30 IComparable – ExampleIComparable – Example class Point : IComparable class Point : IComparable { public int X { get; set; } public int X { get; set; } public int Y { get; set; } public int Y { get; set; } public int CompareTo(Point otherPoint) public int CompareTo(Point otherPoint) { if (this.X != otherPoint.X) if (this.X != otherPoint.X) { return (this.X - otherPoint.X); return (this.X - otherPoint.X); } if (this.Y != otherPoint.Y) if (this.Y != otherPoint.Y) { return (this.Y - otherPoint); return (this.Y - otherPoint); } return 0; return 0; }}
31
Implementing IComparable Implementing IComparable Live Demo
32
The IEnumerable InterfaceThe IEnumerable Interface Iterators and Foreach
33
33 The IEnumerable interface provides collection classes with foreach traversal ( Enumerable in Java) It consists of 4 interfaces: IEnumerable, IEnumerable, IEnumerator, IEnumerator IEnumerable public interface IEnumerable : IEnumerable { IEnumerator GetEnumerator(); IEnumerator GetEnumerator();} // Non-generic version (compatible with the legacy.NET 1.1) public interface IEnumerable : IEnumerable { IEnumerator GetEnumerator(); IEnumerator GetEnumerator();}
34
34 IEnumerator provides sequential read-only, forward-only iterator (see Iterator Design Pattern)Iterator Design Pattern IEnumerator public interface IEnumerator : IEnumerator { bool MoveNext(); bool MoveNext(); void Reset(); void Reset(); T Current { get; } T Current { get; }} public interface IEnumerator { bool MoveNext(); bool MoveNext(); void Reset(); void Reset(); object Current { get; } object Current { get; }}
35
35 The yield return construct in C# simplifies the IEnumerator implementations When a yield return statement is reached The expression is returned, and the current instruction pointer + stack are retained (for later resume) Yield Return in C# public IEnumerator GetEnumerator() { for (int i=100; i<200; i++) for (int i=100; i<200; i++) { yield return i; yield return i; }}
36
Implementing IEnumerable Implementing IEnumerable Live Demo
37
Value Types Values Staying in the Execution Stack
38
38 Stored directly in the program execution stack Can not hold null value Passed by value (by copy) when a method is called Destroyed when the variable goes out of scope Inherit from System.ValueType Value types are: Primitive types ( int, char, float, bool ) Structures (e.g. DateTime ) Enumerations Value Types
39
Reference Types Pointers to Objects in the Heap
40
40 Implemented as type-safe pointers to objects Stored in the dynamic memory (managed heap) null Can hold null value When a method is called passed by reference (by address) Destroyed by the garbage collector when not used Many variables can point to the same object Reference objects are: System.Object, System.String, classes and interfaces, arrays, delegates, pointers, dynamic objects Reference Types
41
Value vs. Reference Types Assigning, Memory Location and Values
42
42 Value types and reference types behave differently When assigning value types, their value is copied to the variable When assigning reference type, only the reference (address) is copied and the objects stays the same Memory location Value types stay in the program execution stack Reference types stay is the dynamic memory (managed heap) Value vs. Reference Types
43
43 Value types can not take null as a value Because they are not pointers (addresses) Value types inherit System.ValueType Reference types inherit System.Object Value type variables can be stored in reference type variables through a technique called "boxing" Values
44
44 Value and Reference Types – Example class RefClass { public int value; } // Reference type struct ValStruct { public int value; } // Value type class TestValueAndReferenceTypes { static void Main() static void Main() { RefClass refExample = new RefClass(); RefClass refExample = new RefClass(); refExample.value = 100; refExample.value = 100; RefClass refExample2 = refExample; RefClass refExample2 = refExample; refExample2.value = 200; refExample2.value = 200; Console.WriteLine(refExample.value); // Prints 200 Console.WriteLine(refExample.value); // Prints 200 ValStruct valExample = new ValStruct(); ValStruct valExample = new ValStruct(); valExample.value = 100; valExample.value = 100; ValStruct valExample2 = valExample; ValStruct valExample2 = valExample; valExample2.value = 200; valExample2.value = 200; Console.WriteLine(valExample.value); // Prints 100 Console.WriteLine(valExample.value); // Prints 100 }}
45
45 Types, Variables and Memory Program execution stack (stack end) (free stack memory) struct2 struct1 class2 class1 (stack start) Variable... 0x00000000...... 2000x0012F674 100 0x0012F678 0x04A41A44 0x0012F67C 0x04A41A44 0x0012F680...... ValueAddress Dynamic memory (managed heap) 200 0x04A41A44...... ValueAddress..............................
46
Value and Reference Types Live Demo
47
Boxing and Unboxing Keeping Value Types in Objects
48
48 Value types can be stored in reference types Boxing and unboxing is done automatically in.NET Boxing == converting a value type to a boxed reference one Unboxing == converting boxed value to a value type In Java and JavaScript boxing / unboxing is implemented with wrapper classes around the primitive types E.g. Java.lang.Integer in Java E.g. Number class in JS Boxing and Unboxing
49
49 1.Allocates dynamic memory for the boxed object A new object in the managed heap 2.Copies the value of the value-type variable From the stack to the boxed object 3.Returns a reference to the boxed object The original value type is stored as part of the boxed object Boxing: How It Works?
50
50 1.If the reference is null A NullReferenceException is thrown 2.If the reference does not hold a valid boxed value An InvalidCastException is thrown 3.The value is pulled from the heap Stored into the stack in a value-type variable Unboxing: How It Works?
51
51 Boxing Value Types i=5(value-type variable in the stack) object obj = i; 5 (boxing) obj (boxedvalue-typevariable in the heap) in the heap) (unboxing) i2 = (int) obj; i2=5(value-type variable in the stack) StackHeap int i=5; int i2;
52
52 Boxing and Unboxing – Example class TestBoxingUnboxing { static void Main() static void Main() { int value1 = 1; int value1 = 1; object obj = value1; // boxing performed object obj = value1; // boxing performed value1 = 12345; // only stack value is changed value1 = 12345; // only stack value is changed int value2 = (int)obj; // unboxing performed int value2 = (int)obj; // unboxing performed Console.WriteLine(value2); // prints 1 Console.WriteLine(value2); // prints 1 long value3 = (long) (int) obj; // unboxing long value3 = (long) (int) obj; // unboxing long value4 = (long) obj; // InvalidCastException long value4 = (long) obj; // InvalidCastException }}
53
Boxing and Unboxing Primitive Types Live Demo
54
54 Boxing and Unboxing – Example interface IMovable { void Move(int x, int y) void Move(int x, int y)} // Bad practice! Structures should hold no logic, but only data! struct Point : IMovable { public int x, y; public int x, y; public void Move(int x, int y) public void Move(int x, int y) { this.x += x; this.x += x; this.y += y; this.y += y; }}
55
Boxing and Unboxing Custom Types Live Demo
56
Passing Parameters ref and out Keywords
57
57 Parameters can be passed in several ways to the methods: in (default) Passed by value for value types Passed by address for reference types out Passed by stack address for both value types and reference types ref Passed by stack address for both value types and reference types Passing Parameters: In, Out and Ref
58
public class Student { public string name; public string name; static void IncorrectModifyStudent(Student student) static void IncorrectModifyStudent(Student student) { student = new Student("Changed: " + student.name); student = new Student("Changed: " + student.name); } static void ModifyStudent(ref Student student) static void ModifyStudent(ref Student student) { student = new Student("Changed: " + student.name); student = new Student("Changed: " + student.name); } static void Main() static void Main() { Student s = new Student("Nakov"); Student s = new Student("Nakov"); Console.WriteLine(s.name); // Nakov Console.WriteLine(s.name); // Nakov IncorrectModifyStudent(s); IncorrectModifyStudent(s); Console.WriteLine(s.name); // Nakov Console.WriteLine(s.name); // Nakov ModifyStudent(ref s); ModifyStudent(ref s); Console.WriteLine(s.name); // Changed: Nakov Console.WriteLine(s.name); // Changed: Nakov }} 58 ref Parameters – Example
59
ref Parameters Live Demo
60
class TestOutParameters { static void Main() static void Main() { Rectangle rect = new Rectangle(5, 10, 12, 8); Rectangle rect = new Rectangle(5, 10, 12, 8); Point location; Point location; Dimensions dimensions; Dimensions dimensions; // Location and dimension are not pre-initialized! // Location and dimension are not pre-initialized! rect.GetLocationAndDimensions(out location, out dimensions); rect.GetLocationAndDimensions(out location, out dimensions); Console.WriteLine("({0}, {1}, {2}, {3})", Console.WriteLine("({0}, {1}, {2}, {3})", location.x, location.y, dimensions.width, dimensions.height); location.x, location.y, dimensions.width, dimensions.height); // Result: (5, 10, 12, 8) // Result: (5, 10, 12, 8) }} 60 out Parameters – Example
61
out Parameters Live Demo
62
Summary 1.The Common Type System (CTS) defines the data types in.NET1.The Common Type System (CTS) defines the data types in.NET 2.System.Object is the base type for all.NET types 3.Object cloning copies the object date3.Object cloning copies the object date Provided by ICloneable Provided by ICloneable 4.IComparable defines object comparison 5.IEnumerable defines an iterator over the elements of the object ( foreach support) 6.Value types hold values in the stack, passed by value6.Value types hold values in the stack, passed by value 7.Reference types hold value in the heap + address in the stack7.Reference types hold value in the heap + address in the stack 62
63
? ? ? ? ? ? ? ? ? https://softuni.bg/courses/oop/ Common Type System
64
License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 64 Attribution: this work may contain portions from "OOP" course by Telerik Academy under CC-BY-NC-SA licenseOOPCC-BY-NC-SA
65
SoftUni Diamond Partners
66
Free Trainings @ Software University Software University Foundation – softuni.orgsoftuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bgforum.softuni.bg
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.