I was astounded recently to have someone from overseas ask for my advice. (Hey, I've got imposter syndrome as bad as anyone.) The young man is studying at Technical University of Chemnitz in Germany. Here's what he said [edited],
I am sharing the code with you. Here in the GiveAction() Method, I am passing the reference of Method1(). Although Method1() is non-static method, still I am able to invoke this method via Action. How is the compiler doing implicit conversion? Could you please share your views on that. As far as I know non-static methods always needs an instance on which these methods are invoked.
This is the code he sent [edited]
class Program
{
int i = 4;
static void Main(string[] args)
{
Program p = new Program();
Action y1 = p.GiveAction();
y1();
y1();
Console.WriteLine();
}
private Action GiveAction()
{
return new Action(Method1);
}
public void Method1()
{
this.i++;
}
}
This was my response:
I've been messing with Action and Func lately (I've got some articles about it on Dev.to)
I've not seen this thing of instantiating the Program class in its own Main method before. I can readily see that it can be done I just never thought of doing it.
Right,
-
GiveAction
andMethod1
are both methods of the class calledProgram
. -
p
is pointed to an instance ofProgram
.p
therefore now has methodsGiveAction
andMethod1
. -
y1
is given the result of runningp
's instance ofGiveAction
which in this case is an Action, a function pointer, top
'sMethod1
method. -
y1
is evaluated twice, causing the Action, the function pointer top
'sMethod1
to be evaluated twice thus incrementing the instance variable ofp
from 4 to 6.
Actions are a bit like JavaScript anonymous functions. That would appear to be the way in which you're using them here.
This is almost equivalent to
function Program() {
var i = 4;
return {
Main: function () {
var p = new Program();
var y1 = p.GiveAction();
y1();
y1();
print(i);
},
GiveAction: function () {
return this.Method1;
},
Method1: function () {
this.i++;
}
}
}
debugger;
var P = new Program();
P.Main();
However, the i
in this implementation doesn't get incremented, so it's not an exact translation.
Okay, community, is what I wrote correct? And how do I get the JavaScript to behave like the C#?
Top comments (2)
Both
Method1()
andGiveAction()
are instance method (as apposed to static methods) and therefor there's no problem at all accessingMethod1()
fromGiveAction()
. Now, let's take a look at the code and add some comments to explain what's going on:Awesome :)