Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern for allowing functions to accept generic types

I've got two classes:

public abstract class Uniform<T>
public class UniformMatrix4 : Uniform<Matrix4>

(So far....there will be more that implement different types)

And now lets say I want to write a function that will accept any uniform object... but I can't do that because there is no class called Uniform, only the generic Uniform<T>. So what's the best approach to solving this problem?

  1. Make Uniform<T> implement IUniform
  2. Make Uniform<T> extend Uniform
  3. Make all my functions that accept a Uniform to be generic too so that they can take a Uniform<T> directly?
like image 725
mpen Avatar asked Dec 31 '11 23:12

mpen


2 Answers

Make your methods generic as well, and you're good.

Note that you always have the choice of using all generic type arguments on the function if needed, like this:

public void MyMethod<TUniform, T>(TUniform uniform) where TUniform: Uniform<T> {...}

The compiler will usually infer the type arguments on his own whenever you have a parameter, so that the call in fact looks like a normal method invocation in the C# source code:

UniformMatrix4 uniform;
MyMethod(uniform); // the types of the generic functions are inferred
like image 147
Lucero Avatar answered Sep 18 '22 01:09

Lucero


Admittedly intimidated to post this answer, but think it may be correct:

 public static Uniform<dynamic> MyMethod(dynamic myObject) { 
      //do stuff    
      return uniform;
    }

Here is a Dino Esposito blog on the topic:

http://msdn.microsoft.com/en-us/magazine/ff796227.aspx

Cheers,

Matt

like image 23
Matt Cashatt Avatar answered Sep 18 '22 01:09

Matt Cashatt