How many methods can a C# class have
Asked Answered
R

9

16

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.

Ruysdael answered 12/9, 2009 at 17:30 Comment(2)
-1 - It Doesn't Matter. See André Hoffmann's excellent answer.Patric
@truewill: disagree 100%. It doesn't matter to you, but it matters to DHornpout. I understand good practice is extremely important, but that's not the question. We shouldn't assume the askers scenario, nor should we demand justifications. we should answer the question, and if necessary, supplement with good practice suggestions.Mayst
R
27

16.7 million per assembly per method (not class).

Rebirth answered 12/9, 2009 at 17:44 Comment(3)
That may be so, but could you mention the source of this information?Crashing
The method definition table only has place for 24 bits of indexes. Simple math. Read the spec :)Rebirth
Actually the MethodDef table doesn't have a specific limit. However, there are only 24 bits available in the index portion of a metadata token, so while you could probably create a .NET assembly with more than 2^24 methods, you could only reference the first 2^24 plus I doubt the CLR would load it.Marked
A
20

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!

Adelleadelpho answered 18/8, 2012 at 1:35 Comment(1)
+1 for being the single actual proper answer. I'd plus ten this answer if possible, especially considering all those other vacuous answer who did get far too many upvotes. Only if you know the actual limitations of something you can work around/with it. Thanks for the example code saving me quite some time and thanks for your excellent book.Quicken
A
17

I don't know how many methods a C# class can have, but I do know that when you're thinking about it you are most certainly doing something wrong.

If there is a limit(which I doubt) it's so high that you won't exceed it. Except you have a really bad class design.

See the anti-pattern "God object".

UPDATE:

Even though I still don't exactly know what you want to achieve, I still believe that you should definitely create a lot of classes with only a few methods for the following reasons:

  • Performance: if you are putting all properties into one class, for every property memory has to be allocated when you create an instance, even if you only need 5% of the properties in your class

  • Modularity: if you create a lot of classes you can make them all implement an interface/abstract class and thereby define a similar structure, which will help making your application more modular

  • Structure: it's pretty straightforward to see which methods use which properties when only they reside in the same class - otherwise things might get really really messy

  • Compiling time: when changing the implementation of one function, the others don't have to be re-compiled, as they are in other classes

Agrestic answered 12/9, 2009 at 17:35 Comment(11)
Please leave a comment when downvoting.Millicent
It is not an answer. How can it help if(for example) DHornpout wants to write c# compiler or something?Countrywoman
To decide whether or not this is helpful we would have to know what exactly he is doing. Since we don't, I assumed the regular case, which doesn't involve building a compiler.Millicent
I guess I need 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.Ruysdael
Could you edit your answer to reflect the 2 possible class designs you are trying to decide between?Millicent
Thank for the thorough update. Yes through some various testing, multiple classes is better than single class with multiple methods. Of course that lead to another question how many classes can a single assembly contains before it is a performance problem. I up vote for your thoughtful and useful suggestion.Ruysdael
Can you give us some numbers? How many classes will you have? How many instances will be created in one run? Maybe you can even tell us what exactly you are doing?Millicent
@andre: -1 Andre, you are 100% correct, but you're simply not answering the question. Too many times fellow SO users spin answers to preach good design. Good, good design is important, but this is why many come to SO, to get obscure questions answered, without having to justify themselves. I think that's fair.Mayst
@andy: I am answering the question, at least in the update. To completely answer his question we'd need more informations. If you read his comment you'd see that he agreed to use multiple classes over multiple methods. Now he just needs to figure out how the performance is when he has many classes. To answer that we'd have to know how many classes he will possibly have. If he wouldn't have to justify himself how could he figure out that what he is doing is against common sense? Discussions aren't a bad thing. It's not like my answer was: No. Can't do. Do this. It's just an opinion after all.Millicent
@andre: fair enough, in this case pointing to good practices actually helped. I think there's always a fine balance to find between questioning whether the question itself is correct, or just answering the question. On one hand some questions are misguided by misinformation, such as DHornpout's. But on the other hand, it's often unhelpful to demand from the asker so much justification ...hmm.... I think we've got a bit meta...Mayst
The "normal" case would be: curiosity. Or is that really so unthinkable?Subtrahend
H
4

The Type.GetMethods method returns an array that must be indexed by an integer so, I would say you can't have more than int.MaxValue methods per class.

Hypsometry answered 12/9, 2009 at 17:46 Comment(0)
Z
2

Look at this: https://softwareengineering.stackexchange.com/questions/193295/implications-of-a-large-partial-class/193304?noredirect=1#193304

Someone actually went through the pain of generating a class with as many methods as possible

Zerk answered 29/3, 2013 at 2:26 Comment(0)
S
1

More than you will ever want to put in a single class.

Stpierre answered 12/9, 2009 at 17:34 Comment(0)
M
0

Yes...

Its called common sense. Try not to overload a class, it will most likely violate the single responsibility principle, and noone will be able to understand it.

After all, a class is there "only to aid the developer, who cant fit more then 7 informations at once into his short term memory" (Yes, i know thats a dangerous statement)

Micromho answered 12/9, 2009 at 17:40 Comment(0)
C
0

I don't think so. However, good software development practices and guidelines when followed and considered should naturally limit the number of properties and methods that a class has to what makes sense and absolute necessity. Such practices include SOLID, KISS (keep it simple), DRY (Don't repeat yourself), composition, refactoring, inheritance, etc.

Checkmate answered 12/9, 2009 at 17:41 Comment(0)
A
0

I have an automated code generation tool and I currently hit the limit between ~5K (which worked) and 10K, which failed

System.TypeLoadException: Type '<the type name>' from assembly '<the assembly name>, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' contains more methods than the current implementation allows.

So this contradicts claims that it is "unlimited".

Afterdamp answered 4/5, 2012 at 17:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.