using System;
namespace Test
{
class MainClass
{
delegate int D(int j);
static void Main()
{
D[] a;
a=new D[100];
for (int i = 0; i < a.Length; i++)
{
a = delegate(int j) { return j * i; };
}
Console.WriteLine(a[5](5));
}
}
}
[.net] Delegates in c#
Here my c# code:
The output is:
500
Shouldn’t that be 25 ? ( a[5] = delegate(int j) { return j * 5; }; )
I have never used C#, but here is what I guess:
1) a(5)==500 for all i
2)
does what you want it to do.
1) a(5)==500 for all i
2)
for (int i = 0; i < a.Length; i++){ int local = i; a = delegate(int j) { return j * local; };}
does what you want it to do.
That code is really messed but here is what I think happened..
when you call :
a[5](5)
it is jumping up to the function definition inside the for loop where i had been left defined at 100. I dont know how you expected i to equal 5 but thats clearly not the case. Unless you copy and store the value its not going to magically store the states for you.
Why dont you use a class like:
class D
{
int _multiplier = 0;
D( int multiplier )
{
_multiplier = multiplier;
}
Execute( int j )
{
return j * _multiplier;
}
}
when you call :
a[5](5)
it is jumping up to the function definition inside the for loop where i had been left defined at 100. I dont know how you expected i to equal 5 but thats clearly not the case. Unless you copy and store the value its not going to magically store the states for you.
Why dont you use a class like:
class D
{
int _multiplier = 0;
D( int multiplier )
{
_multiplier = multiplier;
}
Execute( int j )
{
return j * _multiplier;
}
}
I am doing this just for fun so I'm not searching for an alternative method...
I just want to know why
for (int i = 0; i < a.Length; i++)
{
int local = i;
a = delegate(int j) { return j * local; };
}
woks but
for (int i = 0; i < a.Length; i++)
{
a = delegate(int j) { return j * i; };
}
doesn’t.
I just want to know why
for (int i = 0; i < a.Length; i++)
{
int local = i;
a = delegate(int j) { return j * local; };
}
woks but
for (int i = 0; i < a.Length; i++)
{
a = delegate(int j) { return j * i; };
}
doesn’t.
i is in the scope of the enclosing function, so the value the delegate sees is updated each time around the loop (so it is 100 for all of them by the end). local is in the scope of the for loop.
That's the difference. I hope you wouldn't write production code like this anyway :P.
That's the difference. I hope you wouldn't write production code like this anyway :P.
I agree that this is confusing. Usually primitive types and structs are copied, with delegates you get something similar to a reference to a primitive type.
With a class this kind of behaviour is the one you would expect:
With a class this kind of behaviour is the one you would expect:
for(Int i = new Int(0); i<new Int(100); i.inc()){a[i.value()] = delegate(int j) { return j * i.value(); };}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement