Reputation: 5808
I know I shouldn't have to ask this but whatever it is I am missing is driving me nuts! I have done this many times before and I can only put it down to old age and slight senility.
I have a class with two objects that get initialized in the constructor...
public class EbayFunctions
{
private static ApiContext apiContext = null;
private static List<StoreCategoriesFlattened> storeCategories = new List<StoreCategoriesFlattened>();
public EbayFunctions()
{
ApiContext apiContext = GetApiContext();
List<StoreCategoriesFlattened> storeCategories = GetFlattenedStoreCategories();
}
public string GetStoreCategoryIdForItem(string category)
{
var result = storeCategories.Find(x => x.CCDatabaseMatch == category);
return ""; //Ignore will return a value
}
}
then I have a forms app (test harness) that makes use of the class and on button click I call a method...
namespace EbayTestHarness
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cmdGetEbayStoreCatID_Click(object sender, EventArgs e)
{
EbayFunctions ebf = new EbayFunctions();
string ddd = ebf.GetStoreCategoryIdForItem("Motors > Bikes");
}
}
}
However apiContext
persists between calls but storeCategories
gets populated on EbayFunctions ebf = new EbayFunctions();
and is null when string ddd = ebf.GetStoreCategoryIdForItem("Motors > Bikes");
is called.
I know its something stupid but what am I missing?
Upvotes: 0
Views: 56
Reputation: 152566
Your problem is here:
private static ApiContext apiContext = null;
private static List<StoreCategoriesFlattened> storeCategories = new List<StoreCategoriesFlattened>();
public EbayFunctions()
{
ApiContext apiContext = GetApiContext(); // local!!
List<StoreCategoriesFlattened> storeCategories = GetFlattenedStoreCategories(); // local!!
}
You're not setting the static fields - you're introducing local variables that then go out of scope and are (eventually) garbage collected. Take out the type indicators to set the static fields:
public EbayFunctions()
{
apiContext = GetApiContext();
storeCategories = GetFlattenedStoreCategories();
}
Also, as @PatrickHofman points out, the initialization of static members should be done once - preferably in a static constructor:
static EbayFunctions()
{
apiContext = GetApiContext();
storeCategories = GetFlattenedStoreCategories();
}
Upvotes: 5