C#C
C#3y ago
p. frost

❔ Generic method that takes in a struct and calls the correctly-typed method

I'm working with OpenTK (an OpenGL binding) and I'd like to create a method that allows setting uniforms (basically variables inside of a shader).

The solution I've come up with is the following. For context, Matrix4 is a struct. This method is part of my Shader class, in which I'm trying to abstract the native types.

public void SetUniform<T>(string name, T value) where T : struct
{
    if (typeof(T) == typeof(Matrix4))
    { 
        GL.UniformMatrix4(_uniforms[name], false, (Matrix4)value);
    }
}


The cast (Matrix4)value doesn't work though. I wrote it like this so that I can write a single method to set any type of uniform value, here the only implemented one is Matrix4.

My question is : Is there a way to make this work, or do I have to write a method for each type of argument?
If that's a bad solution, what would be a good one?

(Alternatively, I could abstract uniforms further with an Uniform class so I'm not directly working with the native types in my shader abstraction, but that would also require adding an abstraction for the uniform use cases.)
Was this page helpful?