In JavaScript, it's not uncommon to see self-invoking functions:
var i = (function(x) { return x; })(42); // i == 42
While I'm certainly not comparing the languages, I figured such a construct would be translatable to C#, provided a language version with support:
var i = (delegate(int x) { return x; })(42);
Or:
var i = ((x) => { return x; })(42);
Or even:
var i = (x => x)(42);
However, every version is in error:
Method name expected
Are self-invoking anonymous methods unsupported (due either to explicit forbiddance, or the impossibility of type inference), or is there an error in my attempts?
I'm venturing a guess that because there was no method declaration (Func<T,T>
) against which the types could be inferred, it can't sort out the implied types, figures I meant to call a declared method by name, and really goofed up the syntax.
Errata
Before this question is flooded with:
var i = new Func<int, int>(x => x)(42);
I should say that I was hoping to leverage type inference, but I suppose that may not be possible due to being overly-implicit.
So, clarifying the question a bit; we know we can var i = new Func<int, int>(x => x)(42);
but without creating an instance of, or casting to Func
, is this possible?
Use-Case
For those curious (or concerned) the use case was something like this:
var o = new { PropertyA = () => { // value computation }(), PropertyB = () => { // value computation }(), };
Self-Invoking FunctionsA self-invoking expression is invoked (started) automatically, without being called. Function expressions will execute automatically if the expression is followed by (). You cannot self-invoke a function declaration.
In JavaScript, a “Self-Invoking” function is a type of function that is invoked or called automatically after its definition. The execution of such an anonymous function is done by enclosing it in a parenthesis set followed by another set of parenthesis.
The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .
An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();
var x = ((Func<int, int>)(y => y * 2))(10);
The problem is that when the compiler sees y => y * 2
it classifies it as an Expression
instead of a Func
by default, unless there is some contextual information to let it know it should be a Func
. By casting it to Func
we give it the context it needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With