Search code examples
c#opentk

Calling Method (with any parameter) from parameter


I am trying to write a game with OpenTK. I want to check the error everytime I call something from GL class.

so, let say, I have this class:

public static class GLCheck
{
    public static void Call(function f)
    {
        // Call f function
        CheckError();
    }

    public static void CheckError()
    {
        ErrorCode errorCode = GL.GetError();

        if (errorCode != ErrorCode.NoError)
            Console.WriteLine("Error!");
    }
}

so I can call function like this:

GLCheck.Call(GL.ClearColor(Color.White));
GLCheck.Call(GL.MatrixMode(MatrixMode.Modelview));
GLCheck.Call(GL.PushMatrix());

how can I do this? thanks

----------------- Answer: -----------------

thanks for the answer! I just realize all answers are using Delegate (Action or Func<>) On .NET 2.0, this is not available, so you must create your own, here my GLCheck Class:

public static class GLCheck
{
    public delegate void Action();
    public delegate void Action<T1, T2>(T1 arg1, T2 arg2);
    public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);
    public delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
    public delegate TResult Func<TResult>();
    public delegate TResult Func<T, TResult>(T arg);
    public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
    public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3);
    public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);

    public static void Call(Action callback)
    {
        callback();
        CheckError();
    }

    public static void Call<T>(Action<T> func, T parameter)
    {
        func(parameter);
        CheckError();
    }
}

Once again, thanks for the answer!


Solution

  • It won't be quite as tidy, but you can do this pretty easily with Lambda functions:

    GLCheck.Call(() => GL.ClearColor(Color.White));
    GLCheck.Call(() => GL.MatrixMode(MatrixMode.Modelview));
    GLCheck.Call(() => GL.PushMatrix());
    

    And Call would be defined like this:

    public static void Call(Action a)
    {
        a();
        CheckError();
    }
    

    In the case of methods GL methods without parameters, you can pass them in a bit more cleanly:

    GLCheck.Call(GL.PushMatrix);
    

    (note that there are no () after PushMatrix.)