C# Method parameter incorrectly updates

I have the following C# simple code :

public class Error
{
    public string ErrorDescription { get; set; }
    public string ErrorCode { get; set; }
}

public class Request
{
    public Error RequestError { get; set; }
}

public class Response
{
    public Error ResponseError { get; set; }
}

public Response Process(Request request)
    {
        var r = new Response
        {
            ResponseError = request.RequestError
        };

        r.ResponseError.ErrorDescription = "New Response Description";

        return r;
    }

I call Process through a console app with :

var request = new Request
{
    RequestError = new Error()
    {
        ErrorCode = "Request Error Code",
        ErrorDescription = "Request Error Description"
    }
};

var service = new Service();
var response = service.Process(request);
Debug.WriteLine("request ErrorDescription = " + request.RequestError.ErrorDescription);

Why request.ResponseError.ErrorDescription is equal to "New Response Description"; I have not updated request object and it's not called by out/ref. I only update response object that I return.

What am I doing wrong?

Thanks

Jon Skeet
people
quotationmark

This is the start of the problem:

ResponseError = request.RequestError;

You have a single Error object - after that line, your response and request both refer to the same object. Bear in mind that Error is a class, so the values of Request.RequestError and Response.ResponseError are references.

You then modify the object here:

r.ResponseError.ErrorDescription = "New Response Description";

If you still don't fully understand, you might want to read my article on references and values.

people

See more on this question at Stackoverflow