I read in an ebook somewhere (which I'm desperate to find again), that, by using delegates, it is possible to write code which has syntax as follows:
()(); // where delegate precedes this.
Can anyone provide any details how this would be possible/in what situation this would occur?
You can do slightly better than the examples given so far, in fact... you can extend it arbitrarily:
class Test
{
delegate Hofstadter Hofstadter();
static void Main()
{
// Unfortunately I'm clearly not as smart as the real thing
Hofstadter douglas = () => null;
douglas()()()()()()();
}
}
And here's another horrible alternative, for extra ASCII art:
class Test
{
delegate __ ___();
delegate ___ __(___ _);
static void Main()
{
___ _ = () => null;
_ ()((_))();
}
}
Please never ever, ever do this.
EDIT: One last one - although it's as much about just replacing things with underscores as anything else, and reusing names wherever possible:
class Test
{
delegate void _();
delegate __<_> ___<_>();
delegate ___<_> __<_>(___<_> ____);
static ___<_> ____<_>(___<_> ____) { return ____; }
static __<_> ____<_>() { return ____<_>; }
static void Main()
{
((__<_>)____)(____<_>)();
}
}
Here's a sample program that demonstrates this:
using System;
class Program
{
static Action GetMethod()
{
return () => Console.WriteLine("Executing");
}
static void Main()
{
GetMethod()();
Console.ReadKey();
}
}
That being said, I wouldn't ever do this in production code. It's very unexpected.
Edit: Just in case you want to see something even uglier... [especially the "()()[()=>{}]()
"]:
using System;
class Program
{
static void Main()
{
(new Program()).Confusion();
Console.ReadKey();
}
public Action this[Action index]
{
get {
return () => Console.WriteLine("Executing");
}
}
Func<Program> GetInstance()
{
return () => this;
}
void Confusion()
{
// This is particularly ugly...
GetInstance()()[()=>{}]();
}
}
You just need a little self referencing, and you can call it as many times as you like:
delegate Foo Foo();
class Program {
static void Main(string[] args) {
Foo f = null;
f = () => f;
// Add more "()" as you feel like...
f()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()();
}
}
static void Foo()
{
Console.WriteLine("Hello World!");
}
static Action Bar()
{
return new Action(Foo);
}
static void Main()
{
Func<Action> func = new Func<Action>(Bar);
func()();
Bar()();
}
prints
Hello World! Hello World!
This works, because func()
and Bar()
return an Action
delegate which can be invoked using normal method invocation syntax.
Something like:
delegate void FunctionA();
delegate FunctionA FunctionB();
void TestA() { }
FunctionA TestB() { return TestA; }
void Main()
{
TestB()();
}
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