Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many methods can a C# class have

Is there a limitation on number of properties, methods a C# class can have?

I do a quick skim at Standard ECMA-334 and did not find any information on it.

Before jumping into why a class with many methods are bad design, I want to be more clear on the intention. Of course I will not be writing a class with large number of methods manually. The reason I am asking this is I need to generate a large number of execution units by code. I am debate between have multiple classes with single method or one large class with multiple methods.

So for this question, I am only interest if is there a limit and what is the limit for number of properties, methods.

like image 657
DHornpout Avatar asked Sep 12 '09 17:09

DHornpout


People also ask

How many methods can a class have in C#?

The correct answer, in the current CLR implementation, is ushort. MaxValue - 15. This can be tested as follows: AppDomain appDomain = AppDomain.

How many methods a class can have?

b) A class should contain an average of less than 30 methods, resulting in up to 900 lines of code.

What is methods in C?

A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments.

Are methods public by default in C#?

Interfaces may declare static members, including nested types, methods, indexers, properties, events, and static constructors. The default access level for all interface members is public .


2 Answers

16.7 million per assembly per method (not class).

like image 170
leppie Avatar answered Oct 20 '22 03:10

leppie


The correct answer, in the current CLR implementation, is ushort.MaxValue - 15. This can be tested as follows:

AppDomain appDomain = AppDomain.CurrentDomain;

AssemblyName aname = new AssemblyName ("MyDynamicAssembly");

AssemblyBuilder assemBuilder =
  appDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.Run);

ModuleBuilder modBuilder = assemBuilder.DefineDynamicModule ("DynModule");

TypeBuilder tb = modBuilder.DefineType ("Widget", TypeAttributes.Public);

for (int i = 0; i < ushort.MaxValue - 15; i++)
{
    MethodBuilder methBuilder = tb.DefineMethod ("SayHello" + i, MethodAttributes.Public, null, null);
    ILGenerator gen = methBuilder.GetILGenerator();
    gen.EmitWriteLine ("Hello world");
    gen.Emit (OpCodes.Ret);
}
Type t = tb.CreateType();
object o = Activator.CreateInstance (t);

The question is relevant if you're using Reflection.Emit to create a typed DataContext to back a database (as LINQPad does). With enough stored procedures, you can hit this limit!

like image 39
Joe Albahari Avatar answered Oct 20 '22 03:10

Joe Albahari