Exactly what happens when Foo.SomeCheck() is called in the Bar class? Is an instance of Foo created in order to call SomeCheck()? If so, is this instance stored on the heap, and is it ever collected through garbage collection?
public class Foo() {
public static bool SomeCheck() {
return true;
}
}
public class Bar() {
public void SomeMethod() {
// what happens when we access Foo to call SomeCheck?
if (Foo.SomeCheck()) {
//do something
}
}
}
Static methods differ from instance methods in that no instance of the class they belong to needs to have been created for them to be called. When you call a static method, you in fact make the call using the name of the type rather than an instance of the type – which should reinforce the idea that static methods are not called on instances. That bears repeating and emphasis: No instance of a class is required to call a public static method of that class.
Now, your example is malformed, but presumably,the line:if( Foo.SomeCheck() )is calling theSomeCheckstatic method using the name of the type:Foo– not an instance. Bar however, has to be instantiated in order to make this call –however, in your example, you don’t have a well-formed instance ofBar. Code generally has to exist inside a method (or a member initializer) – which you don’t have here.To respond to the other parts of your question. Assuming the code in question is part of an instance method, something has to instantiate
Bar– and invoke that method. That something would have to create or otherwise acquire an instance ofBar. Reference types will always be creted on the heap – but that’s largely irrelevant here.As for garbage collection, you normally shouldn’t worry about this. The .NET runtime makes sure to cleanup instances that are not referenced from any root object in your program. Roots are typically instances that reside somewhere on the callstack or are referenced by static members of one type or another. Since we don’t see any code here that creates or references
Barit’s impossible to say when it will be collected. For instance, ifBaris a singleton and stored somewhere in a static variable, it may live for a very long time – perhaps the entire lifetime of the program. You can’t really know without seeing all of the code that manipulates and managesBar.