Common Type System.NET Types Hierarchy, Cloning, Comparing, Collection Iterators, Value and Reference Types SoftUni Team Technical Trainers Software University.

Post on 29-Dec-2015

217 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

Common Type System.NET Types Hierarchy, Cloning,

Comparing, Collecti on Iterators,Value and Reference Types

SoftUni TeamTechnical TrainersSoftware Universityhttp://softuni.bg

2

1. What is Common Type System (CTS)?

2. The System.Object type

3. Operators is and as

4. Object Cloning

5. The IComparable<T> Interface

6. The IEnumerable<T> interface

7. Value Types and Reference Types

8. Passing Parameters: in, out, ref

Table of Contents

What is Common Type System (CTS)?

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)

ASP.NETWeb Forms, MVC,Web API, SignalR

WindowsForms

WPF / XAML

WinJS /Win8

C# VB.NET C++ F# …

FCL

CLR

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 System.Object

What is CTS?

6

.NET CTS Types Hierarchy Types

(System.Object)

Value Types(System.ValueType ) Reference Types

Primitive Value Types

Structures

Enumerable Types

Self Descriptive Types

Pointers

Classes ArraysBoxed Value

TypesInterfaces

User Defined Classes

Delegates

Dynamic

The System.Object TypeThe Parent of All .NET Types

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 objects ToString() – represents the object as a string GetHashCode() – evaluates the hash code

(used with hash-tables)

System.Object Type

Overriding the Virtual Methods in System.Object

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 The same applies for the operators == and != You can override Equals() and use it for == and !=

Overriding System.Object's Virtual Methods

11

Overriding System.Object Methods – Examplepublic class Student{ public string Name { get; set; } public int Age { get; set; } public override bool Equals(object param) { // If the cast is invalid, the result will be null Student student = param as Student; // Check if we have valid not null Student object if (student == null) return false; // Compare the reference type member fields if (!Object.Equals(this.Name, student.Name)) return false; // Compare the value type member fields if (this.Age != student.Age) return false; return true; }

// the example continues

12

Overriding System.Object Methods – Example (2)

public static bool operator == (Student student1, Student student2) { return Student.Equals(student1, student2); }

public static bool operator != (Student student1, Student student2) { return !(Student.Equals(student1, student2)); }

public override int GetHashCode() { return Name.GetHashCode() ^ Age.GetHashCode(); }}

13

Classes can override the virtual ToString() method

Overriding ToString()

public class Student{ public string Name { get; set; } public int Age { get; set; }

public override string ToString() { return string.Format("Student: {0}, Age: {1}", this.Name, this.Age); }}

Overriding the Virtual Methods in System.Object

Live Demo

15

The System.Object type has some other methods, which are inherited by all .NET types: GetType()

Returns the 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.Object

is and as Operators

isas

17

The is operator Checks if an object is an instance of a given type Polymorphic operation

5 is Int32 5 is object 5 is IComparable<int>

The as operator Casts a reference type to another reference type Returns null value if it fails, e.g. if the types are incompatible

Type Operators in C#

class Shape { }class Triangle : Triangle { }class TestOperatorsIsAndAs{ static void Main() { Object objBase = new Shape();

if (objBase is Shape) Console.WriteLine("objBase is Shape"); // Result: objBase is Shape

if (! (objBase is Triangle)) Console.WriteLine("objBase is not Triangle"); // Result : objBase is not Triangle

if (objBase is System.Object) Console.WriteLine("objBase is System.Object"); // Result : objBase is System.Object // the example continues

18

Operators is and as – Example

19

Operators is and as – Example (2) Shape b = objBase as Shape; Console.WriteLine("b = {0}", b); // Result: b = Shape

Triangle d = objBase as Triangle; if (d == null) Console.WriteLine("d is null"); // Result: d is null

Object o = objBase as object; Console.WriteLine("o = {0}", o); // Result: o = Shape

Triangle der = new Triangle(); Shape bas = der as Shape; Console.WriteLine("bas = {0}", bas); // Result: bas = Triangle }}

Operators is and asLive Demo

Object Cloning

22

In programming cloning an object means to create an identical copy of a 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 Cloning

23

Types which allow cloning should implement the ICloneable interface

The Clone() method in ICloneable The only method of the interface Returns an identical copy of the object

Returns object must be cast later

You decide whether to create a deep or a shallow copy or something mixed

Object Cloning (2)

class LinkedList<T> : ICloneable{ public T Value { get; set; } public LinkedList<T> NextNode { get; private set; }

public LinkedList(T value, LinkedList<T> nextNode = null) { this.Value = value; this.NextNode = nextNode; }

object ICloneable.Clone() // Implicit implementation { return this.Clone(); } // the example continues

24

Object Cloning – Example

25

Object Cloning – Example (2)public LinkedList<T> Clone() // our method Clone(){ // Copy the first element LinkedList<T> original = this; T valueOriginal = original.Value; LinkedList<T> result = new LinkedList<T>(valueOriginal); LinkedList<T> copy = result; original = original.NextNode;

// Copy the rest of the elements while (original != null) { valueOriginal = original.Value; copy.NextNode = new LinkedList<T>(valueOriginal); original = original.NextNode; copy = copy.NextNode; } return result;}

Deep and Shallow Object CloningLive Demo

The IComparable<T> InterfaceComparing Objects

28

The System.IComparable<T> interface Implemented by the types, which can be compared

(ordered in increasing order)

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<T> Interface

29

IComparable<T> – Exampleclass Point : IComparable<Point>{ public int X { get; set; } public int Y { get; set; }

public int CompareTo(Point otherPoint) { if (this.X != otherPoint.X) { return (this.X - otherPoint.X); }

if (this.Y != otherPoint.Y) { return (this.Y - otherPoint); }

return 0; }}

Implementing IComparable<T>Live Demo

Exercise in Class

The IEnumerable<T> InterfaceIterators and Foreach

33

The IEnumerable<T> interface provides collection classes with foreach traversal It consists of 4 interfaces: IEnumerable<T>, IEnumerable, IEnumerator<T>, IEnumerator

IEnumerable<T>

public interface IEnumerable<T> : IEnumerable{ IEnumerator<T> GetEnumerator();}

// Non-generic version (compatible with the legacy .NET 1.1)public interface IEnumerable : IEnumerable{ IEnumerator GetEnumerator();}

34

IEnumerator<T> provides sequential read-only, forward-only iterator (see Iterator Design Pattern)

IEnumerator<T>

public interface IEnumerator<T> : IEnumerator{ bool MoveNext(); void Reset(); T Current { get; }}

public interface IEnumerator{ bool MoveNext(); void Reset(); object Current { get; }}

35

The yield return construct in C# simplifies the IEnumerator<T> implementations When a yield return statement is reached

The expression is returned, and the current element is retained (to resume later)

Yield Return in C#

public IEnumerator<int> GetEnumerator(){ for (int i = 100; i < 200; i++) { yield return i; }}

Implementing IEnumerable<T>Live Demo

Value TypesValues Staying in the Execution Stack

38

Stored directly in the program execution stack Cannot 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

Reference TypesPointers to Objects in the Heap

40

Implemented as type-safe pointers to objects Stored in the dynamic memory (managed heap) 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

Value vs. Reference TypesAssigning, Memory Location and Values

value types reference types

42

Each Windows process is assigned its own memory area The stack holds called methods and

their local variables Has fixed size (cannot grow) Each thread is granted its own stack

The heap holds dynamically allocated objects during execution Can dynamically grow Shared between all threads

Process Memory

Stac

k Heap

Heap

Program.exe memory

int

bool

long

"hello"

new Person()

new FileStream()

new Thread()

43

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 object 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

44

Value types cannot 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"

Value vs Reference Types (2)

45

Value and Reference Types – Example class Student { public int age; } // Reference typestruct Number { public int value; } // Value typeclass TestValueAndReferenceTypes{ static void Main() { Student pesho = new Student(); pesho.age = 100; Student gosho = pesho; gosho.age = 200; Console.WriteLine(pesho.age); // Prints 200 Number num1 = new Number(); num1.value = 100; Number num2 = num1; num2.value = 200; Console.WriteLine(num1.value); // Prints 100 }}

46

Value types' values are directly pushed onto the stack Reference types have their pointer pushed onto the stack

Stack Variable Allocation

int a = 5;00E525B3 mov dword ptr [ebp-3Ch],5 int b = 41;00E525BA mov dword ptr [ebp-40h],29h string name = "Pesho";00E525C1 mov eax,dword ptr ds:[39021F0h] 00E525C7 mov dword ptr [ebp-44h],eax

StackVariable Address Value

ebp (stack start) … …

a 0xBA2A1A01

5

b 0xBA2A1AFD

41

name 0xBA2A1AF9

eax

(free stack memory) … …

(stack end) 0x00000000

47

Types, Variables and Memory

Program execution stack

(stack end)

(free stack memory)

struct2

struct1

class2

class1

(stack start)

Variable

...0x00000000

......

2000x0012F674

1000x0012F678

0x04A41A440x0012F67C

0x04A41A440x0012F680......

ValueAddress

Dynamic memory (managed heap)

"Pesho"0x04A41A44

......

ValueAddress

......

......

......

......

......

Value and Reference TypesLive Demo

Boxing and UnboxingKeeping Value Types in Objects

50

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

Boxing and Unboxing

51

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

52

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?

53

Boxing Value Types

i=5(value-typevariable inthe stack)

object obj = i;5

(boxing)

obj

(boxedvalue-typevariable in the heap)

(unboxing)

i2 = (int) obj;

i2=5(value-typevariable inthe stack)

Stack Heap

int i=5;

int i2;

54

Boxing and Unboxing – Example class TestBoxingUnboxing{ static void Main() { int value1 = 1; object obj = value1; // boxing performed

value1 = 12345; // only stack value is changed

int value2 = (int)obj; // unboxing performed Console.WriteLine(value2); // prints 1 long value3 = (long) (int) obj; // unboxing long value4 = (long) obj; // InvalidCastException }}

Boxing and Unboxing Primitive TypesLive Demo

56

Boxing and Unboxing – Example interface IMovable{ void Move(int x, int y)}

// Bad practice! Structures should hold no logic, but only data!

struct Point : IMovable{ public int x, y; public void Move(int x, int y) { this.x += x; this.y += y; }}

Boxing and Unboxing Custom TypesLive Demo

Passing Parametersref and out Keywords

59

Parameters can be passed in several ways to 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

public class Student{ public string name; static void IncorrectModifyStudent(Student student) { student = new Student("Changed: " + student.name); } static void ModifyStudent(ref Student student) { student = new Student("Changed: " + student.name); } static void Main() { Student s = new Student("Nakov"); Console.WriteLine(s.name); // Nakov IncorrectModifyStudent(s); Console.WriteLine(s.name); // Nakov ModifyStudent(ref s); Console.WriteLine(s.name); // Changed: Nakov }}

60

ref Parameters – Example

ref ParametersLive Demo

class TestOutParameters{ static void Main() { Rectangle rect = new Rectangle(5, 10, 12, 8); Point location; Dimensions dimensions;

// Location and dimension are not pre-initialized! rect.GetLocationAndDimensions(out location, out dimensions);

Console.WriteLine("({0}, {1}, {2}, {3})", location.x, location.y, dimensions.width, dimensions.height); // Result: (5, 10, 12, 8) }}

62

out Parameters – Example

out ParametersLive Demo

Summary

1. 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 data Provided by ICloneable<T>

4.IComparable<T> defines object comparison

5.IEnumerable<T> defines an iterator over theelements of the object (foreach support)

6. Value types hold values in the stack, passed by value

7. Reference types hold value in the heap + address in the stack64

License

This course (slides, examples, demos, videos, homework, etc.)is licensed under the "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International" license

66

Attribution: this work may contain portions from "OOP" course by Telerik Academy under CC-BY-NC-SA license

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education,

Profession and Job for Software Developers softuni.bg

Software University @ Facebook facebook.com/SoftwareUniversity

Software University @ YouTube youtube.com/SoftwareUniversity

Software University Forums – forum.softuni.bg

top related