© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
19 replies
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
Matrix4
is a
struct
struct
. This method is part of my
Shader
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);
    }
}
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
(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
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
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.)
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Creating a method that takes a generic method and its variadic parameters as arguments and call it i
C#CC# / help
11mo ago
❔ generic class in generic method
C#CC# / help
3y ago
✅ Specialising a generic method
C#CC# / help
4y ago
✅ Two methods: struct and non-struct
C#CC# / help
2y ago