CAREFUL
It is generally a horrible idea to have, or depend on, side effects in your code. For instance, if you have a generic “compute interest” function, you probably wouldn't want it to also set the current interest rate in your monthly reports. This sort of side effect may work, but may easily lead to maintenance problems. If such a case was desireable, it should be renamed to reflect it's “set rate and compute interest” purpose.
I just noticed a large side effect in SharePoint template list pages. I had put some code at the top of template files such as AllItems.aspx to do create a custom header and discovered a huge problem. Look at this example code. Do you see the problem?
int a = Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(Context).Lists["Picture Library"].Items.Count;
Once this code refers to a picture library, the “context“ of the AllItems.aspx will be for a “picture library.“ In other words, it may show you the “Shared Documents“ or the “Tasks“ for a site, but the context links such as “Explorer View“ or “Active Tasks“ will be missing, and you will find links such as “Slide Show“ in its place.
Merely by referencing another library (actually the “Items“ must be loaded/iterated), in the current web context, the system is changing information about the list it is displaying. SharePoint must “establish“ the current library (changing the internal state) for the rest of the list template page to display, and even simple object model interrogations run the risk of “establishing“ a different current library.
RESULT
I discovered that you MUST NOT refer to the current SPWeb or SPSite context objects whenever possible, or at least know which properties are “safe” (don't change the internal state of the object). The following code (as compared to the previous example) is actually safe.
SPWeb web; int b = (web = new Microsoft.SharePoint.SPSite(SPControl.GetContextWeb(Context).Url).OpenWeb()).Lists["Picture Library"].Items.Count; web.Dispose();
Notice how this line uses the “Url” of the web context to create a new SPWeb, and then once the information is gathered, the SPWeb is disposed.
I don't know if this occurs when the code is added to the AlternateHeader Aspx file, or if it only kicks in if the list template files (such as AllItems.aspx) are modified directly, but I did solve my problem by carefully examining my code for any references to SPControl and GetContext.