Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I declare a function pointer inside a function?

I'm confused with the C# ways of declaring function pointers. I'd like to declare one-line a function pointer variable inside a function, without having to add class members or stuff like that.

What I'm trying is:

System.Func<KeyCode, bool> inputCheck = activeCharacter.continuous_fire ? Input.GetKey : Input.GetKeyDown;

I've tried to also use Action (but apparently it doesn't return a value) and delegate, but apparently I got it wrong.

Can I do this somehow (i.e. I'm just getting the syntax wrong), or the only way to do that is by first declaring a delegate prototype?

edit: to clarify, currently I have to do this:

    bool do_fire=false;
    if (activeCharacter.continuous_fire)
    {
        if (Input.GetKey( Fire ))
        {
            do_fire=true;
        }
    }
    else
    {
        if (Input.GetKeyDown( Fire ))
        {
            do_fire=true;
        }
    }

Since this looks awful and redundant (and redundant is almost always wrong), I'd like to just put the Input.* function in a variable and check that.

pseudo-code:

    bool do_fire=false;
    function keyCheck = activeCharacter.continuous_fire ? Input.GetKey : Input.GetKeyDown;
    if (keyCheck( Fire ))
    {
        do_fire=true;
    }
like image 512
o0'. Avatar asked Jul 01 '26 20:07

o0'.


1 Answers

Your code works in principle, the conditional operator is just unable to determine the common type between “method group” and “method group”. The reason for this is that the methods could be overloaded (even though they’re not in your case), and hence can have more than one signature.

You resolve this by casting either of the arguments explicitly to the target delegate type:

Func<KeyCode, bool> checkFire = activeCharacter.continuous_fire ?
        (Func<KeyCode, bool>)Input.GetKey : Input.GetKeyDown;

Furthermore, your test code is needlessly complex, even after you’ve introduced your inputCheck. There’s no need for any if. Assign do_fire directly instead:

bool do_fire = checkFire(Fire);

An additional remark: your coding conventions are a chaotic mix, you should clean this up. C# generally uses PascalCase for public-facing identifiers and all types, and camelCase for the rest. snake_case is never used.

In other words, it should be:

  • activeCharacter.ContinuousFire
  • doFire
  • fire
like image 51
Konrad Rudolph Avatar answered Jul 04 '26 12:07

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!