static class variable scope issue in C# winforms - why doesn't this bit of code work?
-
20-09-2019 - |
Question
I've got two different forms in my WinForms app (MainForm and Form2 say). They both ask for an access of MyDataSet, via a "getInstance" static method. The issue is after MainForm has got an instance, when Form2 needs to get an instance the static "myDataSet" variable is null, whereas I expect to have been already set? Any ideas?
public class MyDataSet
{
public static MyDataSet myDataSet;
// This was null 2nd call to getInstance
private DataSet myData = new DataSet();
public static MyDataSet GetInstance()
{
if (myDataSet == null)
{
return new MyDataSet();
}
else
{
return myDataSet;
}
}
So it almost seems the static "myDataSet" variable isn't working in terms of only having once instance?
Solution
you forgot to assign the newly create instance to myDataset
if(myDataSet == null)
{
myDataSet = new MyDataSet();
}
return myDataSet
OTHER TIPS
You didn't set myDataSet
This is the correct code:
public class MyDataSet
{
public static MyDataSet myDataSet;
// This was null 2nd call to getInstance
private DataSet myData = new DataSet();
public static MyDataSet GetInstance()
{
if (myDataSet == null)
{
myDataSet =new MyDataSet();
}
return myDataSet;
}
public class MyDataSet
{
public static MyDataSet myDataSet;
// This was null 2nd call to getInstance
private DataSet myData = new DataSet();
public static MyDataSet GetInstance()
{
if (myDataSet == null)
{
myDataSet = new MyDataSet(); // Changed at this point
return myDataSet;
}
else
{
return myDataSet;
}
}
Take a look at this article from Jon Skeet. As others have said you are not setting the variable but you might also want to implement a more robust pattern, or perhaps get rid of the singleton. As it is you could end up multiple instances being created of MyDataSet.
I would go with the fourth or fifth version, if you need a singleton.