What is the maximum number of parameters that a C# method can be defined as taking?

不羁岁月 提交于 2019-11-27 03:02:08

问题


I am trying to figure out what the maximum number of parameters a method in C# can have. I've checked everywhere for an answer, including the C# official documentation, MSDN, and a couple of CLR references and I can't find an answer. Does anyone have an answer to this question?


回答1:


Here is your theoretical answer:

In order to push method arguments onto the stack, compiled code has the following MSIL opcodes to choose from:

ldarg.0

ldarg.1

ldarg.2

ldarg.3

ldarg.S

ldarg

ldarg.0 to ldarg.3 is used to push the first 4 method arguments onto the stack (including this as the first argument for instance methods).

ldarg.S takes an 8 bit argument number, and so it can be used to push up to 256 arguments onto the stack.

That leaves us with plain old ldarg, which can handle the most method arguments: it takes an unsigned 16 bit argument number. So the largest number of arguments that can be successfully compiled into valid MSIL is 2^16 = 65,536.

As others have noted, however, there are various practical stack size limits that apply when actually trying to execute your method depending on the platform/architecture of the system. Based on rmiesen's answer, it looks like the current .NET implementation limits the maximum size of the stack at runtime to 2^14.




回答2:


I used a throwaway program to create a program to determine the maximum number of parameters I can pass to a method. Based on the results of my experimentation, the closest to an answer I can find are the following (all of which is only valid on my computer):

  1. A .net application containing a method with 16383 parameters can be compiled, ran, and called (!)
  2. A .net application containing 16384 or more parameters can be compiled, but running such a program throws an unstated exception.
  3. A .net application containing 50000 parameters can also be compiled, but attempting to run such an application results in a StackOverflowException being thrown.
  4. Attempting to compile a .net application containing 100000 parameters or more results in csc.exe giving a compile-time error, stating that the resulting expression is too long or complex to handle.

Aside from that, does anyone have a definitive answer to this question?

P.S. If anyone wants to try this experiment on their computer, you can start with my test program, which can be downloaded https://docs.google.com/open?id=0B1Q3uRTkbsXic2cwUFpXanNkSk0



来源:https://stackoverflow.com/questions/12658883/what-is-the-maximum-number-of-parameters-that-a-c-sharp-method-can-be-defined-as

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!