lets take this example, which I think covers all my questions:
class SomeClass
{
static SomeType PropertyA
{
get
{
if (....)
return MethodA();
else
return MethodB();
}
}
static SomeType MethodA() { ... }
static SomeType MethodB() { ... }
}
will calling a SomeClass.PropertyA property create a memory leak? My opinion is no, since the property itself doesn’t have a backing field, which would create a memory leak. I ask this because I have read that static properties can create memory leak, but I think it is the backing field that is responsible for memory leak, since it holds a reference to instance.
So in above example, MethodA, MethodB, and PropertyA in above example should not create any memory leaks. Am I wrong about this?
Another question I have is: I have lots of classes that mostly do not have a state nor data. They are just acting as a proxy. Some of those methods are called very frequently. My question would be: should I make those classes singleton, static, or regular classes?
Perfect example would be a class that contains 5-10 methods, and executes some SQL queries.
1) If I have them as regular, then I would need to create them very often (on some user reaction), call some method, and then allow the to be garbage collected.
2) choosing between singleton and static, what would be the pros / cons?
3) If I had a class that contains proxy methods, but has 2-3 IDbCommands that contains 10 parameters each, and is beneficial to reuse them, would that change anything in choosing the correct pattern?
Edit: since I got some answers that confused me more, probably due to misunderstanding, I am going to post an answer to my 1st question. I have done a test, where I allocated a large byte array (300MB), which is retrieved through PropertyA (and MethodA). Both PropertyA abd MethodA in above example will not hold a reference to this object, after fetching it, so as soon as calling code is done with array, it will be handled by GC. So in case where we use static property with getter only, or static methods, there should not be any memory leaks.
If you mean they won’t create or hold onto any memory, then that’s true – the property itself will not hold memory.
Static fields do not create a “memory leak” – the type initializer for the type will be run prior to the first use of the class, and, if a field requires memory, the memory for that field will be allocated. This memory is not cleared – if that’s what you mean by a “leak” -but there is no instance to free, so this is expected and desired behavior.