Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring 2014 1 COS 240 Object-Oriented Languages.

Similar presentations


Presentation on theme: "Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring 2014 1 COS 240 Object-Oriented Languages."— Presentation transcript:

1 Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring 2014 1 COS 240 Object-Oriented Languages

2 WHAT YOU WILL LEARN How to define and use collections The different types of collections that are available How to compare types and use the is operator How to compare values and overload operators How to define and use conversions How to use the as operator 2

3 Course Materials – Source Codes http://www.wrox.com/WileyCDA/WroxTitle/productCd-1118314417.html 3

4 Collections Collections enable you to maintain groups of objects. Unlike arrays, which you’ve used in earlier chapters, collections can include more advanced functionality, such as controlling access to the objects they contain, searching and sorting, and more. You’ll learn how to use and create collection classes and learn about some powerful techniques for getting the most out of them. 4

5 Comparisons When dealing with objects, you often want to make comparisons between them. This is especially important in collections, because it is how sorting is achieved. You’ll look at how to compare objects in a number of ways, including operator overloading, and how to use the IComparable and IComparer interface to sort collections. 5

6 Conversions Earlier lectures showed you how to cast objects from one type into another. In this lecture, you’ll learn how to customize type conversions to suit your needs. 6

7 Collections The biggest limitation is that once arrays have been created, they have a fixed size, so you can’t add new items to the end of an existing array without creating a new one. This often means that the syntax used to manipulate arrays can become overly complicated. OOP techniques enable you to create classes that perform much of this manipulation internally, simplifying the code that uses lists of items or arrays. Arrays in C# are implemented as instances of the System.Array class and are just one type of what are known as collection classes. Collection classes in general are used for maintaining lists of objects, and they may expose more functionality than simple arrays. Much of this functionality comes through implementing interfaces from the System.Collections namespace, thus standardizing collection syntax. This namespace also contains some other interesting things, such as classes that implement these interfaces in ways other than System.Array. 7

8 Collections Because the collection’s functionality (including basic functions such as accessing collection items by using [index] syntax) is available through interfaces, you aren’t limited to using basic collection classes such as System.Array. Instead, you can create your own customized collection classes. These can be made more specific to the objects you want to enumerate (that is, the objects you want to maintain collections of). One advantage of doing this, as you will see, is that custom collection classes can be strongly typed. That is, when you extract items from the collection, you don’t need to cast them into the correct type. Another advantage is the capability to expose specialized methods. For example, you can provide a quick way to obtain subsets of items. In the deck of cards example, you could add a method to obtain all Card items of a particular suit. 8

9 Collections 9

10 Using Collections One of the classes in the Systems.Collections namespace, System.Collections.ArrayList, also implements IList, ICollection, and IEnumerable, but does so in a more sophisticated way than System.Array. Whereas arrays are fixed in size (you can’t add or remove elements), this class can be used to represent a variable-length list of items. To give you more of a feel for what is possible with such a highly advanced collection, the following Try It Out uses this class, as well as a simple array. 10

11 Defining Collections One way to create your own strongly typed collection is to implement the required methods manually, but this can be a time-consuming and complex process. Alternatively, you can derive your collection from a class, such as System.Collections.CollectionBase, an abstract class that supplies much of the implementation of a collection for you. This option is strongly recommended. 11

12 12

13 13

14 Indexers An indexer is a special kind of property that you can add to a class to provide array-like access. In fact, you can provide more complex access via an indexer, because you can define and use complex parameter types with the square bracket syntax as you want. Implementing a simple numeric index for items, however, is the most common usage. 14

15 You can add an indexer to the Animals collection of Animal objects as follows: 15

16 Indexers The this keyword is used along with parameters in square brackets, but otherwise the indexer looks much like any other property. This syntax is logical, because you access the indexer by using the name of the object followed by the index parameter(s) in square brackets (for example, MyAnimals[0]). The indexer code uses an indexer on the List property (that is, on the IList interface that provides access to the ArrayList in CollectionBase that stores your items): return (Animal)List[animalIndex]; Explicit casting is necessary here, as the IList.List property returns a System.Object object. The important point to note here is that you defi ne a type for this indexer. This is the type that will be obtained when you access an item by using this indexer. This strong typing means that you can write code such as animalCollection[0].Feed(); rather than: ((Animal)animalCollection[0]).Feed(); This is another handy feature of strongly typed custom collections. In the following Try It Out, you expand the previous Try It Out to put this into action. 16

17 Keyed Collections and IDictionary 17

18 18

19 19

20 20

21 Iterators Earlier you saw that the IEnumerable interface enables you to use foreach loops. It’s often beneficial to use your classes in foreach loops, not just collection classes such as those shown in previous sections. However, overriding this behavior, or providing your own custom implementation of it, is not always simple. To illustrate this, it’s necessary to take a detailed look at foreach loops. The following steps show you what actually happens in a foreach loop iterating through a collection called collectionObject: 1) collectionObject.GetEnumerator() is called, which returns an IEnumerator reference. This method is available through implementation of the IEnumerable interface, although this is optional. 2) The MoveNext() method of the returned IEnumerator interface is called. 3) If MoveNext() returns true, then the Current property of the IEnumerator interface is used to get a reference to an object, which is used in the foreach loop. 4) The preceding two steps repeat until MoveNext() returns false, at which point the loop terminates. 21

22 22

23 23

24 24

25 Iterators and Collections 25

26 26

27 Comparisons There are two types of comparisons between objects: Type comparisons - determining what an object is, or what it inherits from — are important in all areas of C# programming. Often when you pass an object — to a method, for example — what happens next depends on the type of the object. Value comparisons - Value comparisons are also something you’ve seen a lot of, at least with simple types. When it comes to comparing values of objects, things get a little more complicated. You have to define what is meant by a comparison for a start, and what operators such as > mean in the context of your classes. This is especially important in collections, for which you might want to sort objects according to some condition, perhaps alphabetically or according to a more complicated algorithm. 27

28 Type Comparisons 28

29 Boxing and Unboxing 29

30 30

31 Boxing 31

32 Unboxing 32

33 The is Operator 33

34 Value Comparisons 34

35 Operator Overloading 35

36 36

37 37

38 38

39 39

40 40

41 41

42 42

43 43

44 The IComparable and IComparer Interfaces 44

45 45

46 46

47 47

48 48

49 Sorting Collections 49

50 CONVERSIONS Thus far, you have used casting whenever you have needed to convert one type into another, but this isn’t the only way to do things. Just as an int can be converted into a long or a double implicitly as part of a calculation, you can define how classes you have created can be converted into other classes (either implicitly or explicitly). To do this, you overload conversion operators, much like other operators were overloaded earlier in this lecture. You’ll see how in the first part of this section. You’ll also see another useful operator, the as operator, which in general is preferable to casting when using reference types. 50

51 Overloading Conversion Operators As well as overloading mathematical operators, as shown earlier, you can define both implicit and explicit conversions between types. This is necessary if you want to convert between types that aren’t related — if there is no inheritance relationship between them and no shared interfaces 51

52 Examples 52

53 53

54 54

55 The as Operator 55

56 56

57 57

58 More reading: Karli Watson et all, Beginning Visual C# 2012 Programming, Wrox, Jonh Wiley & Sons, 2013 CHAPTER 11: Collections, Comparisons and Conversions. 58

59 59 Questions?


Download ppt "Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring 2014 1 COS 240 Object-Oriented Languages."

Similar presentations


Ads by Google