Concepts of Programming Languages

(Sean Pound) #1
9.9 Generic Subprograms 427

9.9.3 Generic Methods in C# 2005


The generic methods of C# 2005 are similar in capability to those of Java 5.0,
except there is no support for wildcard types. One unique feature of C# 2005
generic methods is that the actual type parameters in a call can be omitted if the
compiler can infer the unspecified type. For example, consider the following
skeletal class definition:

class MyClass {
public static T DoIt<T>(T p1) {

...
}
}


The method DoIt can be called without specifying the generic parameter if
the compiler can infer the generic type from the actual parameter in the call.
For example, both of the following calls are legal:

int myInt = MyClass.DoIt(17); // Calls DoIt<int>
string myStr = MyClass.DoIt('apples');
// Calls DoIt<string>

9.9.4 Generic Functions in F#


The type inferencing system of F# is not always able to determine the type of
parameters or the return type of a function. When this is the case, for some
functions, F# infers a generic type for the parameters and the return value.
This is called automatic generalization. For example, consider the following
function definition:

let getLast (a, b, c) = c;;

Because no type information was included, the types of the parameters and
the return value are all inferred to be generic. Because this function does not
include any computations, this is a simple generic function.
Functions can be defined to have generic parameters, as in the following
example:

let printPair (x: 'a) (y: 'a) =
printfn "%A %A" x y;;

The %A format specification is for any type. The apostrophe in front of the type
named a specifies it to be a generic type.^9 This function definition works (with
generic parameters) because no type-constrained operation is included.


  1. There is nothing special about a—it could be any legal identifier. By convention, lowercase
    letters at the beginning of the alphabet are used.

Free download pdf