Passing a function as a parameter?

Hello folks,

I’m trying to build a sorta of interface class like this:

public static float simple (float t)
{
return t;
}

public static float quadratic (float t)
{
return t*t;
}

public static float getResult (float a, float b, float t)
{
a + b * simple(t);
}

In another script, I’m calling:

float r = FakeScript.getResult(x, y, t);

Which works. But if I want to extend my interface so that when calling getResult I can also choose wheter to use simple(t) or quadratic(t) without mayor changes on the function’s body, what do I have to do? With some googling I’ve found out that delegates might be the best option, but I couldn’t find any example that might work on my script. Any other suggestion?

Thanks in advance.

Sounds like you really might like to consider using a strategy pattern.

1 Like

Kinda…

But I was thinking something more similar to this: http://amazingretardo.simiansoftwerks.com/2011/01/23/a-robust-c-interpolation-animation-system/ ← this is an animation system, but the concept I want to achieve is the same.

Hi @hedgeh0g

“I want to extend my interface so that when calling getResult I can also choose wheter to use simple(t) or quadratic(t) without mayor changes on the function’s body, what do I have to do? With some googling I’ve found out that delegates might be the best option”

I’ve been learning how to use delegates. The syntax isn’t hard, but they can be used in couple of different ways. In this case, you don’t have to use variables or multicasting, just define the type of method signature in your method, and then pass methods with similar signature, then Invoke, or just call the method, both work the same I think. There is no need to use specialized delegates like Func, Action, Predicate etc, you can also define your own using delegate keyword.

void Start ()
{
    var resultA = getResult(1,2,3, simple);
    Debug.Log("with myDel1: " + resultA);
    var resultB = getResult(1,2,3, quadratic);
    Debug.Log("with myDel2: " + resultB);
}

public static float simple (float t)
{
    return t;
}

public static float quadratic (float t)
{
    return t*t;
}

public static float getResult (float a, float b, float t, Func<float,float> myDelegate)
{
    return a + b * myDelegate.Invoke(t);
}
1 Like

You could use an enum as a parameter and use a switch / if-else block in your main function.

If you are wanting to follow SOLID principles, this would violate the “O”. :slight_smile:

In essence, the solution proposed in that link appears somewhat simiilar to the strategy pattern. I guess it’s debatable whether it is prefereable to use an interface or a delegate to achieve a similar result.

2 Likes

You can look for example here how it is implemented.

Yes! This is exactly what I was looking for!.

Thank you all. :slight_smile: