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?
All parameters are passed by value. ListingFilters is a Reference Type, it points to an object in heap memory, so it's "value" is a memory address. When you pass it to a function as a parameter the parameter's "value" is a reference to the same object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With