0

I have a question regarding parameters passed by value in C#: There is a function which is called to compare two complex objects "Umfrage" using memory stream, TeamId should be excluded from that comparison:

public static bool CompareSurveys(Umfrage obj, Umfrage obj1)
    {
        obj.TeamId = null;
        obj1.TeamId = null;

        using (MemoryStream memStream = new MemoryStream())
        {
            if (obj == null || obj1 == null)
            {
                if (obj == null && obj1 == null)
                    return true;
                else
                    return false;
            }

            BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
            binaryFormatter.Serialize(memStream, obj);
            byte[] b1 = memStream.ToArray();
            memStream.SetLength(0);

            binaryFormatter.Serialize(memStream, obj1);
            byte[] b2 = memStream.ToArray();

            if (b1.Length != b2.Length)
                return false;

            for (int i = 0; i < b1.Length; i++)
            {
                if (b1[i] != b2[i])
                    return false;
            }
            return true;
        }
    }

When I call the method and pass the parameters by value, however, TeamId is set to null anyway. How is that possbile when only the value is passed?

Survey.TeamId = "1";
Debug.WriteLine(Survey.TeamId);
if (ModelValidator.CompareSurveys(@survey, Survey))
{
    return BadRequest("No changes were applied");
}
Debug.WriteLine(Survey.TeamId);

Thanks in advance :)

  • 1
    Assuming `Umfrage` is a class, then although you may be passing the reference by value it's still a reference. Any change you make will be to the same object other areas of your code presumably also have a reference to. – Charles Mager Jan 17 '16 at 12:20
  • Thank you very much, that should be it :) Sorry I didn't recognise there was already a question like mine. – Michael Heribert Jan 17 '16 at 12:34

1 Answers1

0

The function parameters are two Objects.

If you change some object property in this function these properties will be changed outside the function.

But if in your function you do obj = new Umfrage(); and will change properies all properties won't be changed outside.

Roman
  • 11,966
  • 10
  • 38
  • 47