-2

I have an problem to make class as value type. This is my example:

class exampleClass
{
    private List<string> temp = new List<string>();

    public exampleClass(List<string> list)
    {
        temp = list;
    }

    public List<string> list { get { return temp; } }
}

... and initialize window:

public MainWindow()
{
    List<string> exampleList = new List<string>();
    exampleList.Add("TEST");
    Klasy.exampleClass test = new Klasy.exampleClass(exampleList);
    exampleList.Clear();
    InitializeComponent();
}

My question is: How to save value of list in exmapleClass when I clear exampleList. What I should change in class to make it independent of the exampleList?

Thanks

jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
  • Copy all the elements not the list reference. – arekzyla May 16 '18 at 09:39
  • 1
    Possible duplicate of [How do I clone a generic list in C#?](https://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c) – N.K May 16 '18 at 09:40
  • The least you could do when downvoting, is explaining why. He won't be able to figure it out, he is new to the site. Also OP, you should take the [StackOverflow's Tour](https://stackoverflow.com/tour) and take a look at the [ask] page before posting new questions, in order to understand how the site works. – N.K May 16 '18 at 09:42

1 Answers1

0

You are passing the list reference, instead of that creates a new list instance and pass it to exampleClass so that even when exampleList is clear, it would not impact the exampleClass.

    public MainWindow()
    {
        List<string> exampleList = new List<string>();
        exampleList.Add("TEST");
        Klasy.exampleClass test = new Klasy.exampleClass(new List<string>(exampleList));
        exampleList.Clear();
        InitializeComponent();
    }
user1672994
  • 10,509
  • 1
  • 19
  • 32
  • It should not be the responsibility of the user of this class to guarantee that it works as desired. The class itself is responsible by creating a new list instance in the constructor. Otherwise 9 of 10 people will use this class in a wrong way. – Tim Schmelter May 16 '18 at 12:26