I try to use data after I downloaded it from an API. Example of my code:
private int id;
public MainPage()
{
InitializeComponent();
SomeFunction();
}
public void SomeFunction()
{
DownloadFromAPI("url to api");
MessageBox.Show(id.ToString()); //<< Returns 0
}
public void DownloadFromAPI(DownloadStringCompletedEventArgs url)
{
//code to retrieve data (singel id)
id = Int16.Parse(data);
MessageBox.Show(id.ToString()); //<< Returns the correct number, like 14
test();
}
private void test()
{
MessageBox.Show(id.ToString()); //<< Even Returns the correct number 14
}
How is it possible to load the id information after DownloadFromAPI("url to api"); is finished. so i get the right number (14) instead of 0?
I suspect your method actually looks like this:
That’s declaring a new local variable within the method, rather than assigning a value to the instance variable.
However, personally, I’d often prefer to write the method to return the value instead:
Of course if this really is natural state within the object, it may make sense – but often it can be simpler to write code which just computes a value and returns it, than getting into mutation territory.