views:

332

answers:

4

Hi,

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?

+6  A: 

you forgot to assign the newly create instance to myDataset

if(myDataSet == null)
{
    myDataSet = new MyDataSet();
}
return myDataSet
pm100
Doh... Thanks guys
Greg
+2  A: 

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;

    }
Ngu Soon Hui
+1  A: 
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;
        }
    }
Philip Schlump
A: 

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.

JoshBerke