In C# (.NET) how exactly methods (virtual, static, non-virtual) impact on class size?
Each method takes memory to hold its byte code. The code exists once for each method¹, not once for each instance.
Adding and removing instance methods (virtual or non-virtual) won't change the size of your allocated objects. This is not like C++, where adding virtual methods sometimes does increase the size of your allocated objects. Like C++, static methods won't change the size of your allocated objects.
¹ For generic methods, one copy exists for each set of type(s) it's instantiated with.
Edit: In response to the comments, I'll go into more detail.
@Richard: that may or may not be true (it can vary). Only one copy of the IL byte code is ever needed. One method descriptor block is needed for the open constructed method and closed constructed method, plus descriptors for constructed instances that still contain generic type parameters (method with generic arguments in a generic-parameterized base type of a generic type definition). Generally one copy of the native code would be kept for each closed constructed instance that's a value type plus one for zero or more reference types, but there could be zero (not JIT'd/just interpreted) or two or more (baseline and optimizing compiler, where one or more callstacks haven't left the baseline version since the method was recompiled with the optimizing JIT). Edit again: You are correct in that the generic parameter constraints allow just one copy of the native code for all reference types it's instantiated with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With