The Freya Programming Language

Generic methods

See also

A method can also have its own set of formal generic parameters, even when the method is being defined in a non generic class.

Generic methods

A generic method header is declared by including a bracket delimited list of formal generic parameters, just before the optional parameter list:

MathTools = static class
public
    method Min[X(IComparable)](Item1, Item2: X): X;
end;

As the example shows, you can include constraints, as in generic type declarations. You can use the new method this way:

var s1: String := 'First string';
var s2: String := 'Second string';
Console.WriteLine(MathTools.Min[String](s1, s2));

You can also drop the type argument list in order to let the compiler to infer which type parameters are required for the method call to make sense:

var s1: String := 'First string';
var s2: String := 'Second string';
Console.WriteLine(MathTools.Min(s1, s2));

This technique is known as type inference, and it does not always succeeds. For example, assuming we have a generic Min method, the compiler cannot infer a signature for this method call:

MathTools.Min(1.1, 2);

Though there is an implicit conversion from System.Int32, the type of the second parameter, to System.Double, the type of the first parameter, the compiler choose to ignore it. Including those conversions would complicate the algorithm too much and it would give no corresponding benefits. In that case, you must explicitly supply the type parameter:

MathTools.Min[Double](1.1, 2);

Please note that this happen both in C# and in Freya: it's not a compiler limitation, but a language feature.

See also

The Freya Programming Language
Type declarations
Type members
Methods
Method calls
Generic types
Constructors
User defined operators
Iterators
Fields
Properties
Indexers
Events