7

I need to write a bunch of methods that take 1..N generic type parameters, eg:

int Foo<T1>();
int Foo<T1,T2>();
int Foo<T1,T2,T3>();
...
int Foo<T1,T2,T3...TN>();

Inside Foo() I would like to do something for each type, eg

int Foo<T1,T2,T3>() {
    this.data = new byte[3]; // allocate 1 array slot per type
}

Is there any way to parameterize this so that I am not editing every variation of Foo(), something analogous to:

int Foo<T1,T2,T3>() {
    this.data = new byte[_NUMBER_OF_GENERIC_PARAMETERS];
}

Ideally, I'd also like to be able to get an array or collection of the types as well:

int Foo<T1,T2,T3>() {
    this.data = new byte[_NUMBER_OF_GENERIC_PARAMETERS];

    // can do this
    Type [] types = new Type[] { T1, T2, T3 };
    // but would rather do this
    Type [] types = _ARRAY_OR_COLLECTION_OF_THE_GENERIC_PARAMETERS;
}
3
  • It doesn't really make sense within the context of the C# type system to have variadic generic parameter lists - how would you make a method with those types in its signature? And if you never use the type parameters in a method signature, it would be more appropriate to just use a collection of Types directly. (Unless you're trying to capture the compile-time types of a variadic parameter list but that doesn't really make sense either - a params list is an array of a predetermined type.)
    – millimoose
    Aug 4, 2013 at 16:50
  • Have a look at this, stackoverflow.com/questions/44153/… , howevere I suspect it's more trouble than it's worth. Aug 4, 2013 at 16:50
  • Take a look at Jon Skeet's answer at stackoverflow.com/questions/213333/…. You may be able to use the params keyword, depending on your needs.
    – Kirk
    Aug 4, 2013 at 16:52

4 Answers 4

8

You can read the current generic parameters and their number from the MethodInfo.GetGenericArguments array.

You can retrieve the MethodInfo for your current method by using the MethodBase.GetCurrentMethod method.

Note that you will still need to supply several generic overloads of your method with different numbers of generic parameters, as C# and the CLI do not support variadic generic parameter lists.

So, your code sample for the method with three generic parameters could be written like this:

int Foo<T1,T2,T3>() {
    MethodInfo mInfo = (MethodInfo)MethodBase.GetCurrentMethod();
    Type[] types = mInfo.GetGenericArguments();

    this.data = new byte[types.Length];
}
4
  • Thank you sir! (I think there is a typo in your reply- it should be GetGenericArguments() instead of GenericTypeArguments())
    – CoderBrien
    Aug 4, 2013 at 16:53
  • @CoderBrien: You're right - GenericTypeArguments exists for the Type class. Corrected. Aug 4, 2013 at 16:57
  • I know you're trying to avoid setting types and data "statically", i.e. using information you have at compile-time, but take note that this approach moves the burden to run-time; that is, this dynamic approach using Reflection has a performance hit that the static approach doesn't have (because the compiler would do all that work). Aug 4, 2013 at 17:04
  • 1
    i understand the perf implications of reflection. it's not an issue for my use case. i'm not trying to avoid using compile time info. i'm trying to minimize code maintenance for my 1..N replicated methods.
    – CoderBrien
    Aug 4, 2013 at 17:16
2

1) You can get the number of template arguments via reflection: http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx . This way, you can have common implementation for each Foo. In each Foo you can just call:

FooImpl();

The only difference (regarding the "GetCurrentMethod") is that you'll need to get method info of the previous method:

StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();

2) You could generate all Foo versions at runtime - all would share the same implementation of calling FooImpl only. Some details on generating methods at runtime: Creating a function dynamically at run-time and here: http://msdn.microsoft.com/en-us/library/exczf7b9.aspx

1

The .NET framework regards a generic class or method with N type parameters as having a different name from one having more or fewer. It would probably be possible without a huge change to the framework to arrange things so that calling a function

foo<T>(autogeneric ref T it)

as:

foo(1, "George", 5.7);

would get translated as to:

struct foo99 {public int p1; public string p2; public double p3};
...
foo99 temp99;
temp99.p1 = 1;
temp99.p2 = "George";
temp99.p3 = 5.7;
foo1(ref temp);

That would allow a generic method to efficiently accept an arbitrary number of parameters. Being able to pass such anonymous structure by ref might not seem terribly useful, but it could be very powerful when combined with lambdas.

Normally, closing over local variables in a lambda expression would require hoisting the local variables to a heap object and building a delegate which targets that heap object. If one could use the above style, one could instead of creating a persistent closure object and a delegate and passing the delegate, simply hoist the appropriate variables to a structure and pass a byref to it along with a static delegate. This would only work in cases where the called routine wouldn't have to persist the passed-in closure, but on the flip side the caller would know that the called routine wouldn't be persisting the closure. Further, while no .NET languages would support such a thing and some framework changes might be required to allow code which did this to be volatile, passing by reference a structure some of whose members were also byrefs could make it possible for a lambda to access the enclosing procedure's ref parameters--something which is presently not possible (since there's no guarantee the created delegate wouldn't outlive the scope where it was created). Structures die when the scope they're in dies, so the problem wouldn't have to exist with them.

I wish .NET languages had a convenient way of expressing these concepts. The fact that closures can cause variables' lifetimes to be arbitrarily persisted means that code which has ever used a variable in a closure must assume that outside code could change it at any time. A struct-based approach wouldn't have that issue.

0

No. You can not use the Type parameter as you want. But you could use something like Tuple. It allows you to Wrap generics. But you can not use the TypeParamter itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.