Please navigate to the bottom of the page for Table of Contents

Sunday, May 22, 2011

Pass by value versus reference in C#

Functions in C# may have a sequence of parameters. There are 3 ways a parameter can be passed into a function:

  • Pass by value (default way – no prefix; assumes that the variable value is set before the function is called)
  • Pass by reference (prefix with keyword ref; assumes that the variable value is set before the function is called)
  • Pass by reference (prefix with keyword out; assumes that the variable value will be set by the calling function)

When a variable is passed by reference using ref modifier, both the variables point to the same memory location. Note, that 2 variables do get created; but they point to the same memory location pointing at the same object. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword.

Similarly, the out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

Let's now review this simple series of functions to review the important differences between pass by value, pass by reference using ref and pass by reference using out. Also note the differences in behavior for value types and objects when passed to functions.

using System;

namespace SimpleCodingQuestions
{
class Program
{
/// <summary>
/// When a value type is passed by value
/// changes to the passed parameter
/// does not affect the original value
/// </summary>
/// <param name="input"></param>
public static void PassByValue(int input)
{
input = input + 10;
Console.WriteLine("In function PassByValue: input = {0}", input);
}

/// <summary>
/// when a value is passed by reference
/// any changes to the parameter in the
/// function affects the parameter
/// outside the function
/// </summary>
/// <param name="input"></param>
public static void PassByRef(ref int input)
{
input = input + 50;
Console.WriteLine("In function PassByRef: input = {0}", input);
}

/// <summary>
/// when a value is passed by reference
/// any changes to the parameter in the
/// function affects the parameter
/// outside the function
/// </summary>
/// <param name="input"></param>
public static void PassByOut(out int input)
{
// when out is used, the parameter needs to be
// initialized before it can be used
input = 75;
Console.WriteLine("In function PassByOut: input = {0}", input);
}

/// <summary>
/// When objects are passed, they are implicitly passed
/// as reference
/// any changes made in the function
/// will reflect outside also
/// </summary>
/// <param name="emp"></param>
public static void PassingObjectsByValue(Employee emp)
{
emp.Name = "PassingObjectsByValue";
Console.WriteLine("In function PassingObjectsByValue: employee name = {0}", emp.Name);
}

/// <summary>
/// When objects are passed, they are implicitly passed
/// as reference
/// any changes made in the function
/// will reflect outside also
/// THE REF KEYWORD IS NOT NEEDED HERE
/// IT IS EXACTLY THE SAME AS ABOVE FUNCTION
/// </summary>
/// <param name="emp"></param>
public static void PassingObjectsByRef(ref Employee emp)
{
emp.Name = "PassingObjectsByRef";
Console.WriteLine("In function PassingObjectsByRef: employee name = {0}", emp.Name);
}

static void Main(string[] args)
{
// demo of passing value types vy value, ref and out
int input = 5;
Console.WriteLine("In Main: input = {0}", input);
PassByValue(input);
Console.WriteLine("In Main after calling PassByValue: input = {0}\n", input);
PassByRef(ref input);
Console.WriteLine("In Main after calling PassByRef: input = {0}\n", input);
PassByOut(out input);
Console.WriteLine("In Main after calling PassByOut: input = {0}\n", input);

// demo of passing objects by value and ref
Employee emp = new Employee() { Id = 5, Name = "Test" };
Console.WriteLine("In Main: Employee Name = {0}", emp.Name);
PassingObjectsByValue(emp);
Console.WriteLine("In Main after calling PassingObjectsByValue: Employee Name = {0}\n", emp.Name);
PassingObjectsByRef(ref emp);
Console.WriteLine("In Main after calling PassingObjectsByRef: Employee Name = {0}\n", emp.Name);
}
}

/// <summary>
/// Dummy class for demonstrating passing objects
/// </summary>
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
}


I know this is a long program but note the functions, their invocations in the main and the corresponding output below.


image 


As you can see, PassByValue() function's changes to the local variable did not affect the main value, but passing by ref and passing by out did change the value in the main() function. Also, note that objects are inherently passed by reference.

87 comments:

  1. This depicts something of a misleading relationship between passing an object and passing an object with ref. They aren't really the same. They happen to be the same in this case, because you never reassign emp, but should you change your code to do that, it suddenly does matter.

    Ref also sends up a giant red flag to the callers that says "Hey, I may or may not swap out this parameter you're about to give me and replace it with a totally different object, potentially invalidating any instance comparisons you wanted to do."

    ReplyDelete
    Replies
    1. Great post.Thanks for one marvelous posting! I enjoyed reading it;The information was very useful.Keep the good work going on!!

      ETL Testing training in chennai| SAP MM training in chennai | Informatica training in chennai

      Delete
  2. Passing a reference type w/ the "ref" keyword is *not* exactly the same as passing without it in one particular scenario.

    For eg:
    static void Main(string[] args)
    {
    StringBuilder sb=new StringBuilder();
    sb.Append("test");

    RefTest(ref sb);

    Console.WriteLine(sb.ToString());
    }


    static void RefTest(ref StringBuilder sb)
    {
    sb = new StringBuilder();
    sb.Append("newtest");
    }
    In the example above, "newtest" is indeed written to the console.However, if you remove the "ref" from the method def and the call, then "test" is returned instead.

    ReplyDelete
  3. I believe the way it works is that when you pass a reference type (like an object) it passes a POINTER to that object BY VALUE. You'll essentially have 2 pointers to the same memory (one that lives in the scope of the function and one that lives in the calling code) so if you change that memory, you'll see it from both pointers. If you set the parameter to null, it won't affect the calling code's variable. The pointer has been passed by value.

    On the other hand, when you use the ref keyword, you're passing the POINTER BY REFERENCE. You can still change the memory it points to and you'll see it in both places in code as well. However if you set the variable to null, it will change the variable in the calling code to null as well. You've passed the pointer by reference so it's the same pointer.

    ReplyDelete


  4. In your blog I was happy to see your article, better than last time, and have made great progress, I am very pleased. I am looking forward to your article will become better and better.
    hotmail login | red ball | 192.168.1.1

    ReplyDelete

  5. The blog or and best that is extremely useful to keep I can share the ideas of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
    animal jam | five nights at freddy's | hotmail login

    ReplyDelete
  6. The comparison between pass by value and reference in dotnet were very much useful My sincere Thanks for sharing this post
    Dot Net Training in Chennai

    ReplyDelete
  7. nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge so keep on sharing such kind of an interesting blogs.
    dot net training in chennai

    ReplyDelete
  8. Great info about C#. Its very useful to me. And i would like to share your blog to my friends. Its awesome information. thanks... keep update
    Android Training in Chennai | Big data Analytics Training in Chennai

    ReplyDelete
  9. Pretty blog post! I should learn from some useful information for this blog article,
    It 's a great content Keep it useful sharing.
    Selenium Training in Chennai | Selenium Training Institute in Chennai

    ReplyDelete
  10. Great post.Thanks for one marvelous posting! I enjoyed reading it;The information was very useful.Keep the good work going on!!

    ETL Testing training in chennai| SAP MM training in chennai | Informatica training in chennai

    ReplyDelete
  11. Club Pogo are giving a proper guidence how to fix your Gadgets Security.

    ReplyDelete

  12. Before you plan to install antivirus software on your device, you are required to take
    few important steps to avoid software conflicts with the previously installed versions. please visit
    norton activation
    or directly visit
    norton.com/setup .
    you can find more topics there.We love to help you.

    ReplyDelete
  13. This is a wonderful article, Given so much info in it



    translation price per word

    ReplyDelete

  14. Take advantage of the opportunity with brandvaidya
    this is the best digital marketing in terms of SEO, Hq backlinks and brand Promotion along with Movies P.R And Celebrity Profiling.



    ReplyDelete
  15. Really enjoyed this article post.
    https://forums.createspace.com/en/community/people/Ameliaaa
    http://www.authorstream.com/amelia6/
    https://nolamotor.com/NOLAforum/member.php?action=profile&uid=5518
    https://forum.gamevil.com/member.php?578431-amelia6
    http://boost.vforums.co.uk/profile/ameila6
    http://fussballforum-mv.de/forum/index.php?page=User&userID=38618
    http://lovers4u.ca/user/vanessa6
    http://www.fotothing.com/amelia6/

    ReplyDelete
  16. Thanks for sharing superb information’s. Your site is very cool. I’m impressed by the details that you have on this web site. It reveals how nicely you perceive this subject.
    best online translation services
    worldwide translation
    translation chinese to enlgihs
    translation langauge
    multiplie translation services
    translation company
    translation all langauge
    documents translation

    ReplyDelete
  17. Thank you so much for giving pieces of information. POGO online gaming is a perfect platform to make your dream come true. In case if you forget your Pogo account password or are you not able to recover pogo Account. visit here: Recover Pogo Account Password

    ReplyDelete
  18. We have found an easy way to overcome router problem compare to other places on the internet.

    ReplyDelete
  19. The ketogenic diet is a very low-carb, high-fat diet that shares many similarities with the Atkins and low-carb diets. foodsocietyx.com

    ReplyDelete
  20. If any user wants to contact with HP experts to fix HP related problems Every issue is resolved on a priority basis, to provide a most accurate solution. Call or click on below link :

    Customer Support Number.
    HP Customer Support Phone Number.
    HP Printer Support.
    HP Technical Support Number.
    Hp Support Number.
    HP Desktop Customer Support Number.
    HP Laptop Customer Care Number.
    HP Customer Service.
    HP Scanner Support.
    HP Toll Free Number.

    ReplyDelete
  21. Nice thoughts with great helping content. I have also been seeking such thoughfull content to learn and appy in the life. We have also created such type of content on our site. You can refer out site for more ideas.
    Happy New Year 2019 Wishes Messages Sms in Bengali
    Merry Christmas 2018 SMS, Wishes, Messages, Greetings in Bengali
    Merry Christmas 2018 Wishes Messages in Marathi,funny christmas text sms

    ReplyDelete
  22. This is certainly additionally an exceedingly wonderful offer everyone truly qualified on the lookout with. It's always not likely everyday there is chances read a little something. extremely well written article as click here . I will be sure to and return to read more of your useful information. Thanks for the post. I’ll certainly comeback.
    click here
    click here
    click here
    click here
    click here
    click here
    click here
    click here
    click here
    click here

    ReplyDelete
  23. This is certainly additionally an exceedingly wonderful offer everyone truly qualified on the lookout with. It's always not likely everyday there is chances read a little something. extremely well written article as click here . I will be sure to and return to read more of your useful information. Thanks for the post. I’ll certainly comeback.
    click here
    click here

    ReplyDelete
  24. Hi,
    Your article is very informative and has a lot of information. I really like your effort, keep posting.
    pip camera photo editor 2019

    ReplyDelete
  25. Hi,
    Your article is very informative and has a lot of information. I really like your effort, keep posting.
    hungrysharkevolutionmodapk

    ReplyDelete
  26. This article is actually a nice one it helps new internet viewers, who are wishing in favor of blogging. For more information click here latest news and I absolutely love your blog and find almost all of your post’s to be just what I’m looking for. Does one offer guest writers to write content to suit your needs? click here

    ReplyDelete
  27. HP LaserJet Printer Error code 49
    HP Error Code 49/49.WX.YZ
    HP LaserJet Printer Error code 49.WX.YZ

    Wow, this blog is awsome. Thanks for sharing this HP LaserJet Printer.HP LaserJet Printer Error code 49/49.WX.YZ which users face when their device tries to print or try to execute some action that the firmware of the printer is not capable of performing or it can’t carry out the command or it is possible that the command you have given to your device has not been designed to perform. If there is any type of complications you find you can directly visit our website.

    ReplyDelete
  28. Uttar Pradesh Madhyamik Shiksha Parishad (UPMSP) also known as the UP board will declare the UP 12th Science Toppers list 2019. Students are advised to bookmark this page to receive timely updates and news on the UP Board 12th Result 2019.

    ReplyDelete
  29. Bihar Board 12th Result 2019 Announced for Arts, Science and Commerce Group BSEB Intermediate Result 2019 in School wise, biharboard.ac.in Student wise along District wise Merit Toppers lists from Bihar School Examination Board.

    Navodaya Result 2019 with selected list will be announced for 5th to 6th and 7th, 8th,9th, 10th and 12th grade vacant seat admissions JNVST Result 2019 in Jawahar Navodaya Vidyalaya, Download Navodaya 6th Result 2019 with JNV Selected list 2019 Pdf in District wise with waiting listed candidate details.

    The Navodaya Vidhyalaya Samithi is going to announced the JNVST 6th Class Result 2019
    Navodaya result 2019 with Selected Candidate list for 5th to 6th class admission selection test and the NVS officials are ready to announce JNVST 9th Class Result 2019 with school wise selected candidate list for the Lateral Entry test.

    Kar 2nd PUC Result 2019 check Student wise Karnataka PUC Exam Result 2019 in college wise
    pue.kar.nic.in and Student wise online and SMS based service for regular and private students with school wise merit and toppers lists

    Navodaya 6th Class Admission Selection Test Result 2019 Download in School Wise with Selected Candidate list JNVST Result 2019 along Division wise Merit lists, Download JNVST Result 2019 or Navodaya Result 2019 for JNV Selection list for Jawahar Navodaya Vidyalaya Admission Selection test 2019-20.


    ReplyDelete
  30. Nice Stuff!!
    If you have any technical issue or need any technical assistance for AT&T Email, then you can contact AT&T Technical Support Number or you can also visit here:
    AT&T Help Number

    AT&T Support

    AT&T Customer Care

    AT&T Phone Number

    ReplyDelete
  31. Bihar Board 12th Result 2019 Announced for Arts, Science and Commerce Group BSEB Intermediate Result 2019 in School wise, Bihar Intermediate Result 2019 Student wise along District wise Merit Toppers lists from Bihar School Examination Board.

    Navodaya Result 2019 with selected list will be announced for 5th to 6th and 7th, 8th,9th, 10th and 12th grade vacant seat admissions JNVST 6th Result 2019 in Jawahar Navodaya Vidyalaya, Download Navodaya 6th Result 2019 with JNV Selected list 2019 Pdf in District wise with waiting listed candidate details.

    The Navodaya Vidhyalaya Samithi is going to announced the JNVST 6th Class Result 2019 navodaya 6th result 2019 with Selected Candidate list for 5th to 6th class admission selection test and the NVS officials are ready to announce JNVST 9th Class Result 2019 with school wise selected candidate list for the Lateral Entry test.

    Kar 2nd PUC Result 2019 check Student wise Karnataka PUC Exam Result 2019 in college wise karresults.nic.in and Student wise online and SMS based service for regular and private students with school wise merit and toppers lists.

    Navodaya 6th Class Admission Selection Test Result 2019 Download in School Wise with Selected Candidate listJNVST Selection List 2019 along Division wise Merit lists, Download JNVST Result 2019 or Navodaya Result 2019 for JNV Selection list for Jawahar Navodaya Vidyalaya Admission Selection test 2019-20.



    ReplyDelete
  32. Nice Post!!
    At Delta Airlines Reservations: Here you can take 3 miles of round trip hiking with along the paved roads of the parks, it is the best place for the family outing and it is located at the heart of the city. To know more, you can visit here:
    Delta Airlines Reservations Phone Number

    Delta Airlines Phone Number

    ReplyDelete
  33. Nice Blog!!
    Book your Los Angeles flight via Delta Airlines reservation and enjoy it all. To know more, you can visit here:
    Delta Airlines Flights
    Delta Airlines Reservations
    Delta Airlines Booking

    ReplyDelete
  34. Nice!!
    The USA consists of the 50 states which cover the vast area of North America. It is one of the most visited and largest countries in accordance with diverse in the whole world. With all these, there are many more places. To know more, you can visit here: Delta Airlines Reservations Phone Numbers

    ReplyDelete
  35. hello guys i have to provide model papers 2019.
    previous Papers

    ReplyDelete
  36. Kia has a multitude of pictures in various stages of development and has 3 films slated to go into production over the next 9 months, according to prnewswire.com.

    ReplyDelete
  37. Outlook Help
    Outlook Help , If you are facing any issue in your outlook emails and you need any assistance then call my outlook support team they will assist you on over phone call or they will help you by taking remote access. if you need any assistance then call +1-800-284-6979. we provide 24x7 help. feel free to contact us.
    Outlook Help

    ReplyDelete
  38. I have perused your online journal it is exceptionally useful for me.
    Questions Paper

    ReplyDelete
  39. This is really awesome post and very informative there is no doubt about it. found this one pretty nice and it should go in to my collection. very good work!
    Raj Board 10th Varshik Pariksha Model Paper

    ReplyDelete
  40. There are great things happening in energy project finance and Renewables Finance, but it's something of a roller coaster as the industry changes rapidly.

    ReplyDelete
  41. PG Diploma in International Business Operations: One year qualification is degree at unifiedportal-mem.epfindia.gov.in.

    ReplyDelete
  42. Enjoy a private lunch with Kia Jam, film producer and financier.

    ReplyDelete
  43. Getting the information about the various niches is now easier with the Itsmytrend. It is the correct portal for right information.

    ReplyDelete
  44. For air freight to the USA or air freight to the UK, contact International Freight Company CargoMaster, we provide import for consolidation services too.

    ReplyDelete
  45. A coach could not ask for a better player, and person, than Drew Schaefer to be on his team.

    ReplyDelete
  46. Getting seguidores instagram gratis and tanned on Instagram to pump your Insta has become even easier with the services of FollowersBrazil.

    ReplyDelete
  47. We are investors and problem solvers who can buy your house fast with an all Cash Buyers For Houses offer.

    ReplyDelete