Using WPF and .NET 4.0.
I’m downloading some data using WebClient and using DownloadStringCompletedEventHandler to fire off my DownloadCompletedCallback function upon completion.
The issue I’m having is that when DownloadCompletedCallback is called I’m trying to set the contents of a label on the main form and am presented with the error.
An object reference is required for the non-static field, method, or property ‘Armory.MainWindow.lblDebug’.
I understand that it’s because the function DownloadCompletedCallback is declared as static but I don’t understand why that matters.
Here’s the code I’m using.
public static void DownloadHTML(string address)
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadCompletedCallback);
client.DownloadStringAsync(new Uri(address));
}
private static void DownloadCompletedCallback(Object sender, DownloadStringCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
{
lblDebug.Content = (string)e.Result;
}
}
From the C# specification:
It is because static methods aren’t part of the object, so they can’t interact with anything that is. They are tied to the class which has no concept of state, so when you call it, the static method has no idea which object the non-static object variables it should interact with.
An example why it’s forbidden:
So now the question becomes which non static variables should it interact with? Should it be
ExampleOneorExampleTwo, or should it just throw an null reference exception. In the first two cases there is no way for the system to know which it should interact with, because you never specified it (or it’d be an instance method). For the third, it’s not really static since you’d need to have an instance to call it. So accessing non-static methods properties etc. has to be forbidden, because there is too much ambiguity not to.