Osy#betaRun it on Osyrin: osyrin.com

Reference / Function

Passing a function by name — method groups

Func<T, R> f = Name; · Apply(Name, …) · xs.Select(Name) · Func<T, R> g = Type.StaticMethod;

A function's NAME, written where a function value is wanted, is that function — `Func<int, int> f = Double;`, `xs.Select(Double)`, `xs.Where(IsDue)`. It works for top-level functions, a class's static methods and the methods of the class you are in.

stable1 example compiled by CIfunctionconstructcsharplinq

Summary#

Name the function where C# would take a delegate:

int Double(int x) => x * 2;
bool IsBig(int x) => x > 2;
int Apply(Func<int, int> f, int x) => f(x);

class Units { public static int ToCents(int whole) => whole * 100; }

[Test]
void A_Name_Is_The_Function() {
  Func<int, int> f = Double;
  Assert.Equal(6, f(3));
  Assert.Equal(8, Apply(Double, 4));
  var xs = new List<int> { 1, 2, 3 };
  Assert.Equal(12, xs.Select(Double).Sum());
  Assert.Equal(1, xs.Where(IsBig).Count());
  Func<int, int> cents = Units.ToCents;
  Assert.Equal(300, cents(3));
}

Signature#

Func<T, R> f = Name;                // a delegate-typed variable
Apply(Name, …);                     // a delegate-typed parameter
xs.Select(Name) / xs.Where(Name)    // any LINQ verb that takes a lambda
Func<T, R> g = Type.StaticMethod;   // a class's static method
var h = Name;                       // typed by the function's own signature

Description#

What is it the same as?#

The lambda that calls it: xs.Select(Double) is xs.Select(x => Double(x)). So everything a lambda can do there, a name can — and a mistake in it (the wrong number of parameters, the wrong type) is reported as that call would be.

Which names work?#

A top-level function, a static method named on its class (Units.ToCents), and — inside a class — that class's own methods by bare name. A name that is ALSO a local or a parameter is that variable, as in C#.

See also#

Related

x => … — lambdas, with or without parameter types

A lambda is an inline function: a parameter list, `=>`, and a body. Its parameter types come from where it is used, or…

LINQ over a local list

Query a local `List<T>`, `HashSet<T>` or `T[]` — of your own `class` values OR of plain scalars like `string[]` and…

`static` methods, `static readonly`, `static class` and extension methods

A `static` member belongs to the type rather than to any instance and is reached on the type name — `Money.Round(x)`…