1

I was working on a project of mine when something didn't work as I expected, and now I am reevaluating my entire being. Take the following class and method:

public class Test{
     public string Name { get; set; }
     public int Value { get; set; }
}
public Test ReturnExample(Test test)
{
     Test example = test;
     example.Name = "abc";
     return example;
}

Now, if I have a FirstValue and a SecondValue:

Test FirstValue = new Test {Name = "First", Value = 8 };
Test SecondValue = new Test {Name = "Second", Value = 12 };

All seems pretty generic and straightforward so far but what surprised me was when you do:

SecondValue = ReturnExample(FirstValue);

What I expected the values to be after was:

    FirstValue:
       Name = "First"
       Value = 8
    SecondValue:
       Name = "abc"
       Value = 8

However, what I got was:

    FirstValue:
       Name = "abc"
       Value = 8
    SecondValue:
       Name = "abc"
       Value = 8

So, what's going on here and what can I change to get what I want?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Bubinga
  • 613
  • 12
  • 29
  • 3
    Start reading about the reference values. – Salah Akbari Nov 12 '20 at 05:46
  • Side note: normally inlining all the code involved into single method would be an explanation that you should be able to do yourself... But since you have a problem with how parameters are passed I don't think you could do that... Hopefully @SalahAkbari comment+answer and canonical duplicate should clarify things. – Alexei Levenkov Nov 12 '20 at 06:39
  • What are you talking about? You commented after I had accepted the answer, so I'm unclear with that you are trying to say – Bubinga Nov 13 '20 at 05:18

1 Answers1

1

Based on this:

Reference Types are used by a reference which holds a reference (address) to the object but not the object itself. Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value. Reference Type variables are stored in a different area of memory called the heap. This means that when a reference type variable is no longer used, it can be marked for garbage collection.

With that being said, if you want your code works as expected you need to do a deep copy instead:

public Test ReturnExample(Test test)
{
    Test example = new Test();
    example.Name = "abc";
    example.Value = test.Value;
    return example;
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • For more complex types, like the one in my program, doing it value by value would be very clunky, are there ways to deep copy more complex types simply? – Bubinga Nov 12 '20 at 06:03
  • 1
    @Bubinga Sure, you can use a tool like AutoMapper for this purpose. Here is an example: https://stackoverflow.com/a/39515990/2946329 – Salah Akbari Nov 12 '20 at 06:04