Hello,

I have an instance called "Instance".

From the button event I try to create 2 Instances of "Instance".
I want those 2 Instances to be completely separate from eachother in terms of the variables that exists inside "Instance".

So for example you can see the List variable: "instanceValues"

However, when I click the button to do a test to see if "instanceValues" is 0 when written to file,
the value is 0 for the first file "D:/test0.txt" but for the second file "D:/test1.txt" the value is 3 which I don't want it to be.

This must mean that the "instanceValues" List variable is not its own in each "Instance" but seems to be shared.

How to make the "Instance" isolated from eachother?

//Form1.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace HelloWorld
{
        private void button1_Click(object sender, EventArgs e)
        {
            HelloWorld.Instance ts = new HelloWorld.Instance();
            ts.doSomething(0);

            HelloWorld.Instance ts2 = new HelloWorld.Instance();
            ts2.doSomething(1);
        }
}
----------------------------------------------------------------------------------------------------------------

//Instance.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace HelloWorld
{
    public class Instance
    {

        static public List<String> instanceValues = new List<String>();
        public void doSomething(int number)
        {
            //Create file
            StreamWriter writer = null; FileStream fs = null;
            fs = new FileStream("D:/test" + number.ToString() + ".txt", FileMode.Create, FileAccess.Write, FileShare.ReadWrite); writer = new StreamWriter(fs);
            writer.WriteLine(instanceValues.Count);
            writer.Close(); fs.Close();

            //Just add something
            instanceValues.Add("a");
            instanceValues.Add("b");
            instanceValues.Add("c");
        }

        class oneclass
        {
            //This function needs to access instanceValues as well
            public void dosomethingelse()
            {
                instanceValues.Add("c");
            }
        }
    }
}

Recommended Answers

All 3 Replies

It is shared because you used "static"

Thanks DaveAmour,

You are right. I took that away and it works.
I didn't know the static did share it.

Thanks

Youre welcome - and now you do know how to share something - this is often more efficient if you have data which doesn't change from instance to instance.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.