340

In C#, I have always thought that non-primitive variables were passed by reference and primitive values passed by value.

So when passing to a method any non-primitive object, anything done to the object in the method would effect the object being passed. (C# 101 stuff)

However, I have noticed that when I pass a System.Drawing.Image object, that this does not seem to be the case? If I pass a System.Drawing.Image object to another method, and load an image onto that object, then let that method go out of scope and go back to the calling method, that image is not loaded on the original object?

Why is this?

3
  • 30
    All variables are passed by value by default in C#. You are passing the value of the reference in the case of reference types. Commented Jan 3, 2012 at 6:22
  • Since there was no code given, it is not really clear what is being asked. Maybe the OP meant image.Load(filename) or maybe they meant image = Image.Load(filename) where image is the function param. Commented Apr 12, 2021 at 19:53

9 Answers 9

690

Objects aren't passed at all. By default, the argument is evaluated and its value is passed, by value, as the initial value of the parameter of the method you're calling. Now the important point is that the value is a reference for reference types - a way of getting to an object (or null). Changes to that object will be visible from the caller. However, changing the value of the parameter to refer to a different object will not be visible when you're using pass by value, which is the default for all types.

If you want to use pass-by-reference, you must use out or ref, whether the parameter type is a value type or a reference type. In that case, effectively the variable itself is passed by reference, so the parameter uses the same storage location as the argument - and changes to the parameter itself are seen by the caller.

So:

public void Foo(Image image)
{
    // This change won't be seen by the caller: it's changing the value
    // of the parameter.
    image = Image.FromStream(...);
}

public void Foo(ref Image image)
{
    // This change *will* be seen by the caller: it's changing the value
    // of the parameter, but we're using pass by reference
    image = Image.FromStream(...);
}

public void Foo(Image image)
{
    // This change *will* be seen by the caller: it's changing the data
    // within the object that the parameter value refers to.
    image.RotateFlip(...);
}

I have an article which goes into a lot more detail in this. Basically, "pass by reference" doesn't mean what you think it means.

14
  • 2
    Your right, I didnt see that! I loading image = Image.FromFile(..) and that was replacing the variable image and not changing the object! :) of course.
    – Michael
    Commented Jan 3, 2012 at 6:33
  • 2
    If we drop keywords ref and out from c#, is it ok to say that c# passes parameters the same way as java does i.e. always by value. Is there any difference with java.
    – broadband
    Commented Jun 3, 2015 at 7:15
  • 2
    @DJMethaneMan: Yes, exactly. That's not changing the parameter (assuming myobj is of some reference type...)
    – Jon Skeet
    Commented Aug 16, 2016 at 19:28
  • 5
    @Vippy: No, not at all. It's a copy of the reference. I suggest you read the linked article.
    – Jon Skeet
    Commented Aug 19, 2016 at 18:52
  • 3
    aaaah, examples 1 & 3 pass a copy of the pointer (address) to the source reference type so initially both the source and local things are looking in the same place at the same object but example one changes the pointer of the local copy inside the method so now that is looking at something else, the original pointer is untouched because it can't be touched. Example 2 (ref) uses the same pointer for both so if you mess with it, it changes both.
    – CAD bloke
    Commented May 6, 2020 at 23:35
115

Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.

When you pass an instance as an argument to the method it passes the copy of the instance. Now, if the instance you pass is a value type(resides in the stack) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.

4
  • 6
    This should be the chosen answer!
    – JAN
    Commented Jan 22, 2020 at 7:47
  • 1
    I agree completely! :)
    – JOSEFtw
    Commented Jan 22, 2020 at 7:51
  • Makes perfect sense. Thankyou so much kind sir. Commented Oct 13, 2022 at 19:07
  • Hopefully helps someone coming from the java world: In this regard, c# is essentially the same as Java. However, what differs is passing reference by ref keyword. Check this out - learn.microsoft.com/en-us/dotnet/csharp/language-reference/…
    – bp4D
    Commented Apr 8, 2023 at 21:41
25

One more code sample to showcase this:

void Main()
{


    int k = 0;
    TestPlain(k);
    Console.WriteLine("TestPlain:" + k);

    TestRef(ref k);
    Console.WriteLine("TestRef:" + k);

    string t = "test";

    TestObjPlain(t);
    Console.WriteLine("TestObjPlain:" +t);

    TestObjRef(ref t);
    Console.WriteLine("TestObjRef:" + t);
}

public static void TestPlain(int i)
{
    i = 5;
}

public static void TestRef(ref int i)
{
    i = 5;
}

public static void TestObjPlain(string s)
{
    s = "TestObjPlain";
}

public static void TestObjRef(ref string s)
{
    s = "TestObjRef";
}

And the output:

TestPlain:0

TestRef:5

TestObjPlain:test

TestObjRef:TestObjRef

3
  • 4
    So basically reference type still NEED TO BE PASSED as reference if we want to see the changes in the Caller function. Commented Jun 2, 2018 at 22:20
  • 7
    Strings are immutable reference types. Immutable means, it cannot be changed after it has been created. Every change to a string will create a new string. That's why strings needed to be passed as 'ref' to get change in calling method. Other objects (e.g. employee) can be passed without 'ref' to get the changes back in calling method. Commented Feb 8, 2020 at 4:00
  • 6
    @vmg, as per HimalayaGarg, this isn't a very good example. You need to include another reference type example which isn't immutable.
    – Daniel
    Commented Mar 3, 2020 at 22:48
19

I guess its clearer when you do it like this. I recommend downloading LinqPad to test things like this.

void Main()
{
    var Person = new Person(){FirstName = "Egli", LastName = "Becerra"};

    //Will update egli
    WontUpdate(Person);
    Console.WriteLine("WontUpdate");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateImplicitly(Person);
    Console.WriteLine("UpdateImplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateExplicitly(ref Person);
    Console.WriteLine("UpdateExplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");
}

//Class to test
public class Person{
    public string FirstName {get; set;}
    public string LastName {get; set;}

    public string printName(){
        return $"First name: {FirstName} Last name:{LastName}";
    }
}

public static void WontUpdate(Person p)
{
    //New instance does jack...
    var newP = new Person(){FirstName = p.FirstName, LastName = p.LastName};
    newP.FirstName = "Favio";
    newP.LastName = "Becerra";
}

public static void UpdateImplicitly(Person p)
{
    //Passing by reference implicitly
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

public static void UpdateExplicitly(ref Person p)
{
    //Again passing by reference explicitly (reduntant)
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

And that should output

WontUpdate

First name: Egli, Last name: Becerra

UpdateImplicitly

First name: Favio, Last name: Becerra

UpdateExplicitly

First name: Favio, Last name: Becerra

3
  • and what about public static void WhatAbout(Person p) { p = new Person(){FirstName = "First", LastName = "Last"}; } . :) Commented Jul 4, 2019 at 5:10
  • 1
    Thanks for the lingpad thing Commented Oct 19, 2020 at 17:37
  • Linux4Life531 try this instead of linqpad its free too...dotnetfiddle.net same thing and you dont need to download Commented Oct 20, 2020 at 22:43
9

When you pass the the System.Drawing.Image type object to a method you are actually passing a copy of reference to that object.

So if inside that method you are loading a new image you are loading using new/copied reference. You are not making change in original.

YourMethod(System.Drawing.Image image)
{
    //now this image is a new reference
    //if you load a new image 
    image = new Image()..
    //you are not changing the original reference you are just changing the copy of original reference
}
1
  • This is the correct way of explaining it . used in binary tree and many non linear data strctures in c#
    – Don Feto
    Commented Apr 13, 2023 at 1:18
4

How did you pass object to method?

Are you doing new inside that method for object? If so, you have to use ref in method.

Following link give you better idea.

http://dotnetstep.blogspot.com/2008/09/passing-reference-type-byval-or-byref.html

3
Employee e = new Employee();
e.Name = "Mayur";

//Passes the reference as value. Parameters passed by value(default).
e.ReferenceParameter(e);

Console.WriteLine(e.Name); // It will print "Shiv"

 class Employee {

   public string Name { get; set; }

   public void ReferenceParameter(Employee emp) {

     //Original reference value updated.
    emp.Name = "Shiv";

    // New reference created so emp object at calling method will not be updated for below changes.
    emp = new Employee();
    emp.Name = "Max";
  }
}
-2

In Pass By Reference You only add "ref" in the function parameters and one more thing you should be declaring function "static" because of main is static(#public void main(String[] args))!

namespace preparation
{
  public  class Program
    {
      public static void swap(ref int lhs,ref int rhs)
      {
          int temp = lhs;
          lhs = rhs;
          rhs = temp;
      }
          static void Main(string[] args)
        {
            int a = 10;
            int b = 80;

  Console.WriteLine("a is before sort " + a);
            Console.WriteLine("b is before sort " + b);
            swap(ref a, ref b);
            Console.WriteLine("");
            Console.WriteLine("a is after sort " + a);
            Console.WriteLine("b is after sort " + b);  
        }
    }
}
-3

In the latest version of C#, which is C# 9 at this time of writing, objects are by default passed by ref. So any changes made to the object in the calling function will persist in the object in the called function.

5
  • 1
    this does not seem to be the case for me...
    – XRaycat
    Commented Oct 15, 2021 at 21:07
  • 1
    What is your source for this? Documentation published this month doesn't mention that. Nor does the documentation for passing reference types. Commented Jan 17, 2022 at 4:09
  • 1
    @ProgrammingLlama Indeed, and it seems like this would break a lot of existing code if it were just changed like that after 8 previous versions.
    – Michael
    Commented Mar 15, 2023 at 22:03
  • 1
    This is not now, nor has it ever been true. On top of the docs already linked by @ProgrammingLlama, here's another one from the C# language reference which, on the very first line lays it out clearly and in italics. Commented Apr 30 at 16:54
  • 1
    Regardless, even were this true, it also doesn’t answer the specific case that the question is asking about. Commented May 1 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.