20

Is there a limit on the amount of generic parameters you can have on a type in .NET? Either hard limit (like 32) or a soft limit (where it somehow effects performance to much, etc.)

What I'm referring to is:

class Foo<T0, T2, T3, T4, etc.> {
}
thr
  • 19,160
  • 23
  • 93
  • 130
  • 1
    Just curious because I can't think of an example....where would this be a problem? :) – Nick Craver Mar 26 '10 at 15:17
  • My guess would be that it's limited by how much memory you have, but why would you ever need so many types passed into a class? – adam0101 Mar 26 '10 at 15:19
  • When doing statically typed (and type-inferred) closures for a dynamic language on the .NET – thr Mar 26 '10 at 15:19
  • 14
    Yes, there's a practical limit. The one you'll know you've passed when the rest of your team stops talking to you. – Hans Passant Mar 26 '10 at 15:20
  • 7
    When did the flaming redditors take over SO? Used to be a friendly helpful place, sigh. – thr Mar 26 '10 at 15:21
  • @thr - Like it or not it's an accurate answer...sanity of dealing with so many type parameters it most likely going to be the limiting factor here. – Nick Craver Mar 26 '10 at 15:23
  • @Nick Craver: Or not, since no human ever needs to handle it in my case, it's all done internally in the language compiler/runtime. – thr Mar 26 '10 at 15:24
  • @thr - The first time you have to debug it, a human has to read it though, can't assume it'll always "just work" – Nick Craver Mar 26 '10 at 15:26
  • 1
    .NET 4 offers `Action` and `Func` delegates with up to **16** `in` parameters now, so I think that'll do for a while. – herzmeister Mar 26 '10 at 15:28
  • Whenever I see a question like this I always cringe. Something is very wrong with this project. – NotMe Mar 26 '10 at 16:32

2 Answers2

25

From the C# 2.0 language spec

8.16.3 Multiple type parameters Generic type declarations can have any number of type parameters.

Mark
  • 9,966
  • 7
  • 37
  • 39
22

Anonymous types in C# 3.0 are actually generic, for reasons which I should probably blog about at some point. When we designed anonymous types we realized that of course people could be creating anonymous types with potentially hundreds of fields, so we did a lot of testing of the performance of generics with lots of type parameters.

We didn't find any notable problems.

However, what we consider acceptable, you might not. My advice: try it and see. Write up some benchmarks, execute them, and then you'll be reasoning from empirical data, rather than reasoning from the guesses of random people on the internet who don't know what your user scenarios are or what performance factors are important to you.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067