The reason you have to use ref is because you are changing the delegate that _del
refers to.
Change your code to the following and you won't need the ref parameter:
static MyDel AI(int c)
{
if(c == 'a')
{
return Attack;
}
if(c == 'i')
{
return Idle;
}
if (c == 's')
{
return SwingSword;
}
if (c == 'w')
{
return (MyDel)Attack + SwingSword;
}
return Idle;
}
C# does not pass by reference unless you specify the ref
keyword. However, since the value of a variable of a delegate type is a reference to a method, the value passed is a reference. Use the ref
keyword and you pass a reference to the variable's store, not the method, thus it becomes possible to change its value.
If the previous paragraph is as clear as mud, take a read of https://stackoverflow.com/a/8708674/7122, which is a very good explanation of pass by value vs pass by reference.