I have been answering MS community postings recently and while checking the web my understanding of the ref keyword was correct in terms in terms of referencing the stack, I found a number of web sites giving false information about a related point. This annoyed me so I though I would correct it here.
Member function definitions are not held in memory allocated to object instances and are not duplicated in memory for each instance of a object you create.
Member functions are held in the class definition in memory in the space place as static methods. There is no heap memory saving by making functions static rather than instance.
Instance methods are largely the same as static methods bar a couple of small differences.
- They are marked in the metadata as instance
- They have an implicit first parameter which is the instance of the object they are running for. This is why in the IL, any intance member access is preceeded by ldarg.0 it loads the instance to the top of the computation stack.
- Methods are not serialized with instances as they are not instance data. Therefore there is no space saving at all by making them static.
- Instance members can be virtual and therefore not open some of the optimizations that can be applied to static methods.
Just though I’d clear that up. I know there may be other differences I haven’t mentioned but the main point is made.