Rob Smyth

Thursday, 28 May 2009

Storing a .Net C# Generic Type Parameter

From time to time I hit the problem where I have a call to a generic method where I need to resuse the generic type for later use. Today I think I found a simple pattern that solves the problem.

A code fragement explains all (I hope):
  public class MyRegister
{
private List<IToken> tokens = new List<IToken>();

public void HasService<T>()
{
tokens.Add(new MyToken<T>());
}

public object[] UseRegisteredGenericTypes()
{
List<object> results = new List<object>();

foreach (var token in tokens)
{
results.Add(token.DoSomethingWithMyType());
}

return results.ToArray();
}
}

public class MyToken<T> : IToken
{
public object DoSomethingWithMyType()
{
// Do the stuff here like ... return myApp.DoStuff<T>();
}
}

No comments: