I have some code that is behaving like my variables are being passed by reference when I don’t think they should be.
In a class library I have
public class ListingHelper
{
public static List<FilterCategory> getListingFilterCertifications(ListingCategory parentListingCategory, ListingFilters filters)
{
...//Building up return object
filters.gradingServiceId = 2;
}
}
In the pageLoad of a page I call this:
private void BindForm()
{
ListingFilters filters = new ListingFilters();
filters.gradingServiceId = 0;
if (filters.gradingServiceId > 0)
{
listCertification.DataSource = ListingHelper.getListingFilterCertificationById(filters.gradingServiceId);
listCertification.DataBind();
}
}
I thought that filters.gradingServiceId should be 0 when I get back from calling my method in the library, but it’s coming back as 2. Are methods parameters to static methods really passed by reference?
Listing Filters:
public class ListingFilters
{
public String state { get; set; }
public int categoryId { get; set; }
public int gradingServiceId { get; set; }
public int gradeId { get; set; }
}
Edit
Thanks for the link Jon. So it sounds like in .net all user created classes are reference types and even when passed by value you aren’t actually sending a copy of the object but instead a pointer to its location in memory.
If that’s the case how would I pass a copy of my filters object to a method so that I can mess around with the values and have them not be affected in the code that called it?
You have conceptualized what pass by reference or pass by value in C# means. If you read the specification:
What is probably confusing you here is when you pass reference type as a value parameter a copy of the object is not made a copy of the pointer to the object is made. So if you make a modification to the object inside the method it will be on the actual object not a copy. Why this is considered pass by value is that the pointer is the value that is being passed. If however, you reassigned the parameter to another object (i.e. change the pointer) this will not persist outside the method unless your parameter is declared with the ref keyword.