The operation you're describing here is usually called "apply", since it is simply applying a function to an argument as an extension method. You ask for a way to do it "innately"; I'm not quite sure what you mean. Function application is already innately built into the syntax of C#. To apply a function F
to an argument a
to get a result r
in C# you do it like this:
r = F(a)
So in your case you would assign the lambda to a variable and then apply it, or, as the other answer notes, cast it to the appropriate function type and apply it.
If you want function application as an extension method that takes a lambda, you'll have to write it yourself.
What you are effectively calling out here is that "let expressions" are missing from C#. What I would really want to write here is:
int value =
let o = panel.Controls.Cast<Control>().Last() in
o.Location.Y + o.Size.Height;
Which many languages support, but C# only supports in query comprehensions.
See my answer to this question for more on "let expressions" in C# and why they would be useful, and how they are equivalent to your application function: DRY (Don't Repeat Yourself) and if assignements
Incidentally, if you name your method Select
and make a double-application version called SelectMany
, then you can use LINQ on... well, anything:
using System;
static class X
{
public static R Select<A, R>(this A item, Func<A, R> selector) =>
selector(item);
public static R SelectMany<A, B, R>(this A item, Func<A, B> toB, Func<A, B, R> toR) =>
toR(item, toB(item));
}
public class P
{
public static void Main()
{
string myString = "hello";
string result = from s in myString
from b in s + "goodbye"
select b.ToUpper() + " " + s;
Console.WriteLine(result);
}
}
That is a bizarrely baroque way to write a simple program, but if you are really bent on making extension methods that do things that are already in the language, you can do it!
Exercise: Implement the identity monad. You are well on your way!