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
}(),
};