Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2006 Pearson Education, Inc. All rights reserved. 1 27 Generics Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides.

Similar presentations


Presentation on theme: " 2006 Pearson Education, Inc. All rights reserved. 1 27 Generics Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides."— Presentation transcript:

1  2006 Pearson Education, Inc. All rights reserved. 1 27 Generics Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides added by L.Lilien are © 2006-2009 Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., emailed) request.

2  2006 Pearson Education, Inc. All rights reserved. 2 27.1Introduction 27.2Motivation for Generic Methods 27.3Generic Method Implementation 27.4Type Constraints 27.5Overloading Generic Methods 27.6Generic Classes

3  2006 Pearson Education, Inc. All rights reserved. 3 27.1 Introduction Generics -New feature of C# 2.0 (2005) -Provide compile-time type safety Catch invalid types at compile time Generics discussed: -Generic methods A single method declaration / A set of related methods -Generic classes A single class declaration / A set of related classes -Generic interfaces A single interface declaration / A set of related interfaces Not discussed: generic structs, generic delegates Modified by L. Lilien

4  2006 Pearson Education, Inc. All rights reserved. 4 27.2 Motivation for Generic Methods Let’s start with a solution that uses no generics Overloaded methods -Perform similar operations on different types of data -Example: Overloaded DisplayArray methods for: int array double array char array Modified by L. Lilien

5  2006 Pearson Education, Inc. All rights reserved. 5 Outline Overloaded Methods.cs (1 of 2) Declare three arrays of different types Method calls that invoke three separate methods (overloaded method) that have the same functionality Accept an int array and output its elements

6  2006 Pearson Education, Inc. All rights reserved. 6 Outline Overloaded Methods.cs (2 of 2) Accept a double array and output its elements Accept a char array and output its elements

7  2006 Pearson Education, Inc. All rights reserved. 7 27.2 Motivation for Generic Methods (Cont.) Study all three DisplayArray methods -The only difference among the three methods: in Array element type (int/double/char) appears in two locations -In parameter type in the Method header (lines: 23, 32, 41) -In foreach statement (lines: 25, 34, 43) Combine three DisplayArray methods into one -Replace the element types with a generic name E -Declare one DisplayArray method Displays the string representation of the elements of an array with elements of any type Modified by L. Lilien

8  2006 Pearson Education, Inc. All rights reserved. 8 Outline PrintArray Method Recall what we used moments ago:

9  2006 Pearson Education, Inc. All rights reserved. 9 27.3 Generic Method Implementation In Fig.27.1 (ed.3), we did not use generic method Now: Reimplement program of Fig.27.1 (ed.3) using a generic method -Method calls are identical -Outputs are identical (string representations of array elements) Generic method declaration -Type parameter list -Delimited by angle brackets ( ) Precedes the method’s argument list Contains one or more type parameters (below: T) -Separated by commas (if > 1 type parameter) -Example: static void DisplayArray (... ) Modified by L. Lilien

10  2006 Pearson Education, Inc. All rights reserved. 10 Outline GenericMethod.cs (1 of 2) Call generic method to print out elements of arrays of different type Note: Main in this slide is an exact copy of Main for OverloadedMethods.

11  2006 Pearson Education, Inc. All rights reserved. 11 Outline GenericMethod.cs (2 of 2) Generic method header Use the type parameter T as an identifier in place of actual type names Type parameter list (here with just 1 element: T) Note: Only 1 generic method instead of 3 overloaded methods for OverloadedMethods. Recall what we used in Fig. 27.1: Output the elements in an array of any type

12  2006 Pearson Education, Inc. All rights reserved. 12 ++ READ LATER++ 27.3 Generic Method Implementation (Cont.) Type parameters e.g.: T in: static void DisplayArray ( T[] inputArray ) -Used to declare: Return type not used in the example above Parameter types e.g.: static void Print Array ( T[] inputArray ) Local variable types e.g.: foreach ( T element in InputArray ) -Act as placeholders for the types of the arguments passed to the generic method -Are identifiers that specify generic type names Modified by L. Lilien

13  2006 Pearson Education, Inc. All rights reserved. 13 27.3 Generic Method Implementation (Cont.) Type inferencing (for implicit type arguments) -E.g., for the call: DisplayArray ( int Array ); (see l.16 of Fig.27.3) -Compiler determines that an exact match occurs if the type parameter T of a generic method is replaced with a type of the elements in method call’s argument e.g., exact match if T in DisplayArray declaration in line 24 of Fig.27.3 is replaced with int for line 16 in Fig.27.3 -Then, compiler sets up a call to the method with that type as the type argument for the parameter T e.g., sets up a call to DisplayArray (defined in l.24-31) with int for T -We could have used explicit type argument(s) to indicate the exact type that should be used to call a generic function e.g., DisplayArray ( int Array ); (could be used in l.16) Modified by L. Lilien

14  2006 Pearson Education, Inc. All rights reserved. 14 ** READ LATER** Common Programming Error 27.1 If you forget to include the type parameter list when declaring a generic method, the compiler will not recognize the type parameter names when they are encountered in the method. This results in compilation errors. e.g.: don’t forget the type parameter list in: static void DisplayArray ( T[] inputArray )

15  2006 Pearson Education, Inc. All rights reserved. 15 ** READ LATER** Good Programming Practice 27.1 It is recommended that type parameters be specified as individual capital letters. Typically, a type parameter that represents the type of an element in an array (or other collection) is named T for “type” or E for “element.”

16  2006 Pearson Education, Inc. All rights reserved. 16 ** READ LATER** Common Programming Error 27.2 A compilation error occurs if the compiler cannot find a single non-generic or generic method declaration that is a best match for a method call, or if there are multiple best matches

17  2006 Pearson Education, Inc. All rights reserved. 17 27.4 Type Constraints Type Constraints -Example: Generic Maximum method Determines & returns the largest of its three arguments (of the same type) Type parameter declares both the method’s return type T and the type T of its parameters E.g.: static T Maximum ( T x, T y, T z ) where T : IComparable // constraint on T -the ‘ where ’ clause defines a constraint on T assures that type T implements the interface IComparable -Interface Icomparable defines method CompareTo - CompareTo is needed to find maximum Example of using CompareTo for T being int - int1.CompareTo( int2 ) returns: a negative integer if int1 < int2 0 if int1 = int2 a positive integer if int1 > int2 - Similarly for T being double and T being char

18  2006 Pearson Education, Inc. All rights reserved. 18 27.4 Type Constraints – Cont. -The method CompareTo is not allowed to be called by a generic method unless the compiler can ensure that the method is provided for every type that will ever be used in the generic code - IComparable allows objects of the same type T to be compared using the method CompareTo

19  2006 Pearson Education, Inc. All rights reserved. 19 ** READ LATER ** 27.4 Type Constraints (Cont.) Type Constraints (Cont.) -In general: One can not call an operator on a generic-type variable unless the compiler can ensure that all types that will ever be used in the generic code (for this variable) support that operator We’ll see how the where clause is used to constrain use to only “ensured” cases

20  2006 Pearson Education, Inc. All rights reserved. 20 ** READ LATER ** 27.4 Type Constraints (Cont. 1) IComparable interface -Allows objects of the same type to be compared Classes of these objects must implement the generic interface IComparable -E.g., Int32 and Double implement the generic interface IComparable E.g., the IComparable objects can be used with the sorting and searching methods of classes in the System.Collections.Generic namespace -We’ll see them used so in Ch.28 – on Collections -The structures underlying the simple types all implement this interface So we can compare, e.g., int1 with int2, char1 with char2, etc. -They declare a CompareTo method for comparing objects Example: Recall that for int1.CompareTo( int2 ) it returns: -a negative integer if int1 < int2 -0 if int1 = int2 -a positive integer if int1 > int2 Modified by L. Lilien

21  2006 Pearson Education, Inc. All rights reserved. 21 ** READ LATER ** 27.4 Type Constraints (Cont.2) Specifying Type Constraints - IComparable objects can be compared -But they cannot be used with generic code by default Because not all types implement interface IComparable -Some types that are not simple do not Restrict the types that can be used with a generic method or class to ensure that they meet certain requirements -This is known as a type constraint Restricts the type of the argument supplied to a particular type parameter -The where clause specifies the type constraint for type parameter T Example generic method with a type constraint: static T Maximum ( T x ) where T : IComparable (first T [after ‘static’] specifies method return type as T) -Requires that T implements IComparable interface Now, all objects of type T used by Maximum are guaranteed to have implementations for all methods defined in the Icomparable interface (e.g., the CompareTo method needed in Fig. 27.4-ed.3) Modified by L. Lilien

22  2006 Pearson Education, Inc. All rights reserved. 22 ** READ LATER ** 27.4 Type Constraints (Cont.3) -C# provides several kinds of type constraints NOTE: We discuss class type and interface type constraints only. 1) Class (or: class-type) constraint (discussed long time ago) -Indicates that the type argument must be an object of a specific base class or one of its derived classes 2) Use the reference-type constraint ( class ) -Indicates that the type argument must be a reference type 3) Use the value-type constraint ( struct ) 4) Interface (or: interface-type) constraint (just discussed) -Indicates that the type argument’s class must implement a specific interface -Indicates that the type argument must be a value type 5) Constructor constraint new() -Indicates that the generic code can use operator new to create new objects of the type represented by the type parameter Must provide public parameterless or default constructor - Ensure that objects of the class can be created without passing constructor arguments

23  2006 Pearson Education, Inc. All rights reserved. 23 ** READ LATER ** 27.4 Type Constraints (Cont.4) -C# provides several kinds of type constraints (cont.) 6) Multiple constraints on a type parameter -Provide a comma-separated list of constraints in the where clause Class constraint, reference type or value type constraint, must be listed first -Only one of these types of constraints can be used for each type parameter -However,can use many constraints of a given type Interface constraints are listed next The constructor constraint is listed last (if there is one) Modified by L. Lilien

24  2006 Pearson Education, Inc. All rights reserved. 24 Outline MaximumTest.cs (1 of 2) Call generic method Maximum with interface type constraint (shown on next slide)

25  2006 Pearson Education, Inc. All rights reserved. 25 Outline MaximumTest.cs (2 of 2) Interface constraint - Indicates that this method requires the type arguments T to implement interface IComparable Example of using CompareTo for int int1.CompareTo( int2 ) returns: - a negative integer if int1 < int2 - 0 if int1 = int2 - a positive integer if int1 > int2 Similarly for double and char Uses type parameter T as the return type of the method and as the type of the method’s three parameters

26  2006 Pearson Education, Inc. All rights reserved. 26 27.5 Overloading Generic Methods Generic method may be overloaded 1) By another generic method with different signature: 2) By non-generic methods.. Details next.. Modified by L. Lilien

27  2006 Pearson Education, Inc. All rights reserved. 27 ** READ LATER ** 27.5 Overloading Generic Methods Generic method may be overloaded 1) By another generic method with different signature: Same method name Different method parameters Example: Generic method DisplayArray could be overloaded with a generic method with the additional parameters lowIndex and highIndex that specify the portion of the array to output. 2) By non-generic methods with: Same method name Any number of parameters Example: Generic method DisplayArray could be overloaded with a non-generic method specific to string s that outputs the string s in neat, tabular format. Modified by L. Lilien

28  2006 Pearson Education, Inc. All rights reserved. 28 ** READ LATER ** 27.5 Overloading Generic Methods Compiler encountering a method call: -Searches for the method declaration that most precisely matches the method name and argument types -Generates an error if: Ambiguity due to multiple possible matches No matches

29  2006 Pearson Education, Inc. All rights reserved. 29 In-class Exercise Write a generic method to find the maximal value in an array. Hint: You might start with writing non-generic method to find the maximal value in an _int_ array, and then "convert" the method into a generic one. Finally, test that it works with >=1 data types (e.g., int and double). Modified by L. Lilien

30  2006 Pearson Education, Inc. All rights reserved. 30 27.6 Generic Classes We just covered generic methods Now: Generic classes -Describe classes in type-independent manner -Use simple, concise notation to indicate the actual type(s) At compilation time, C# compiler: -Ensures the type safety -Replaces type parameters with actual arguments Enables client code to interact with the generic class Modified by L. Lilien

31  2006 Pearson Education, Inc. All rights reserved. 31 ** READ LATER ** 27.6 Generic Classes (Cont.) Components of generic class declaration -Class name -Followed by a type parameter list Optional: constraints on its type parameter s Type parameter T -Represents the element type that is manipulated -Used throughout the class declaration to represent the element type Modified by L. Lilien

32  2006 Pearson Education, Inc. All rights reserved. 32 27.6 Generic Classes – cont. We will implement application using generic class Stack: 1) Without generic methods in test application – generic class & non-generic methods in test application Separate non-generic methods in test application -TestPushDouble() / TestPushInt() <– almost identical, both implemented using Push from Stack -TestPopDouble() / TestPopInt() <– almost identical, both implemented using Pop from Stack 2) With generic methods in test application – generic class & generic methods in test application Generic methods in test application -TestPush <– both implemented using Push from Stack -TestPop <– both implemented using Pop from Stack Modified by L. Lilien

33  2006 Pearson Education, Inc. All rights reserved. 33 27.6 Generic Classes – cont. -Next: generic class & non-generic methods in test application Separate, non-generic methods in test application -TestPushDouble() / TestPushInt() <– almost identical, both implemented using Push from Stack -TestPopDouble() / TestPopInt() <– almost identical, both implemented using Pop from Stack Modified by L. Lilien

34  2006 Pearson Education, Inc. All rights reserved. 34 Outline Stack.cs (1 of 2) Type parameter T is used throughout the Stack class to represent the element type Declare elements as an array of type T Initialize elements to the appropriate size

35  2006 Pearson Education, Inc. All rights reserved. 35 Outline Stack.cs (2 of 2) Throw exception if stack is full Increment top counter to indicate the new top position and store the argument Throw exception if stack is empty Decrement top counter to indicate the new top position and return the original top element

36  2006 Pearson Education, Inc. All rights reserved. 36 ++ READ LATER++ 27.6 Generic Classes (Cont.) In a generic class declaration, the class name is followed by a type-parameter list and, optionally, a constraint on its type parameter. As with generic methods, the type-parameter list of a generic class can have one or more type parameters separated by commas.

37  2006 Pearson Education, Inc. All rights reserved. 37 Outline FullStack Exception.cs Create user-defined (really: programmer-defined) exception for when the stack is full

38  2006 Pearson Education, Inc. All rights reserved. 38 Outline EmptyStack Exception.cs Create customize exception for when the stack is empty

39  2006 Pearson Education, Inc. All rights reserved. 39 ++ READ LATER++ 27.6 Generic Classes (Cont.) The compiler performs type checking on the class’s type parameters to ensure that they can be used with the code in the generic class. The constraints determine the operations that can be performed on the type parameters. The runtime system replaces the type parameters with the actual types at runtime. The scope of a generic class’s type parameter is the entire class.

40  2006 Pearson Education, Inc. All rights reserved. 40 Now, let’s consider an application (Fig. 27.8 - below) that uses the Stack generic class. Outline StackTest.cs (1 of 8 ) Fig. 27.8 | Testing generic class Stack. (Part 1 of 8.) declare variables of type Stack and Stack. The types double and int are the Stack ’s type arguments.

41  2006 Pearson Education, Inc. All rights reserved. 41 Outline StackTest.cs (2 of 8 ) Fig. 27.8 | Testing generic class Stack. (Part 2 of 8.)

42  2006 Pearson Education, Inc. All rights reserved. 42 Outline StackTest.cs (3 of 8 ) Fig. 27.8 | Testing generic class Stack. (Part 3 of 8.)

43  2006 Pearson Education, Inc. All rights reserved. 43 Outline StackTest.cs (4 of 8 ) Fig. 27.8 | Testing generic class Stack. (Part 4 of 8.)

44  2006 Pearson Education, Inc. All rights reserved. 44 Outline StackTest.cs (5 of 8 ) Fig. 27.8 | Testing generic class Stack. (Part 5 of 8.)

45  2006 Pearson Education, Inc. All rights reserved. 45 Outline StackTest.cs (6 of 8 ) Fig. 27.8 | Testing generic class Stack. (Part 6 of 8.)

46  2006 Pearson Education, Inc. All rights reserved. 46 Outline StackTest.cs (7 of 8 ) Fig. 27.8 | Testing generic class Stack. (Part 7 of 8.)

47  2006 Pearson Education, Inc. All rights reserved. 47 Outline StackTest.cs (8 of 8 ) Fig. 27.8 | Testing generic class Stack. (Part 8 of 8.)

48  2006 Pearson Education, Inc. All rights reserved. 48 27.6 Generic Classes – cont. Above: application implemented using generic class Stack without generic methods in test application – generic class & non-generic methods in test application Separate non-generic methods in test application -TestPushDouble() / TestPushInt() <– almost identical, both implemented using Push from Stack -TestPopDouble() / TestPopInt() <– almost identical, both implemented using Pop from Stack Now: application will be implemented using generic class Stack with generic methods in test application – generic class & generic methods in test application Generic methods in test application -TestPush <– both implemented using Push from Stack -TestPop <– both implemented using Pop from Stack Figure 27.9 (next) declares TestPush and TestPop -To push and pop elements from a Stack containing elements of any type T Modified by L. Lilien

49  2006 Pearson Education, Inc. All rights reserved. 49 Outline StackTest.cs (1-2 of 6 )

50  2006 Pearson Education, Inc. All rights reserved. 50 Outline StackTest.cs (3 of 6 ) Fig. 27.9 | Testing generic class Stack. (Part 3 of 6.) Generic method TestPush uses type parameter T to represent the data type stored in the Stack. Recall: The generic interface IEnumerable describes objects that can be iterated over, e.g., using foreach (see Line 42).

51  2006 Pearson Education, Inc. All rights reserved. 51 Outline StackTest.cs (4 of 6 ) Fig. 27.9 | Testing generic class Stack. (Part 4 of 6.)

52  2006 Pearson Education, Inc. All rights reserved. 52 Outline StackTest.cs (5 of 6 ) Fig. 27.9 | Testing generic class Stack. (Part 5 of 6.)

53  2006 Pearson Education, Inc. All rights reserved. 53 Outline StackTest.cs (6 of 6 ) Fig. 27.9 | Testing generic class Stack. (Part 6 of 6.)

54  2006 Pearson Education, Inc. All rights reserved. 54 ++ READ LATER ++ 27.x Final notes on Generics and Inheritance (Recall) Generics and inheritance -Generic classes can be derived from non-generic classes -Generic classes can be derived from other generic classes -Non-generic classes can be derived from generic classes -(and, as we know very well) non-generic classes can be derived from non-generic classes Modified by L. Lilien

55  2006 Pearson Education, Inc. All rights reserved. 55 The End of Ch. 27 - Generics Modified by L. Lilien


Download ppt " 2006 Pearson Education, Inc. All rights reserved. 1 27 Generics Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides."

Similar presentations


Ads by Google