473,386 Members | 2,078 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Passing parameters by reference

110 100+
Expand|Select|Wrap|Line Numbers
  1.  private char[] getSeparators(ref string[] varfiles)
Expand|Select|Wrap|Line Numbers
  1.  private char[] getSeparators(string[] varfiles)

As far as I know, the first piece of code will pass varfiles by reference so that varfiles will be changed by getSeparators when control is passed back to the calling method.


What gets passed to getSeperators by the second piece of code?
Oct 17 '08 #1
6 1346
Curtis Rutland
3,256 Expert 2GB
Objects are always passed via reference, so there should be no difference between the two snippets you just posted.
Oct 17 '08 #2
mldisibio
190 Expert 100+
Actually, this is tricky, and I myself get muddled by it every time. Nonetheless a great question!

In the second snippet, you are indeed passing a reference to the array, but reference is an address, equivalent of a pointer. And since the ref keyword is not used, you are sending a copy of that address/pointer. That means, if you "point" the pointer to a new object/address/array, the original pointer remains intact and continues to point to the original array.

In the first snippet, you pass the pointer by reference, meaning if you "point" the pointer to a new object/address/array, the original pointer now also points to the new object (and leaves the original array with no pointer/reference pointing to it...it is now orphaned).

Below is a slightly modified but simple demonstration that can be found on MSDN or in books which discuss this subtle issue.

Expand|Select|Wrap|Line Numbers
  1.   class RefAndValTest {
  2.     static void Main(string[] args) {
  3.       SendArrayByVal();
  4.       SendArrayByRef();
  5.     }
  6.     // ==============================================================
  7.     // Pass a ref type (class, interface, delegate, object, string) by val and create a new memory allocation
  8.     //  Inside Caller, before calling the method, the first element is: 1
  9.     //  Inside the method, the first element is: -3
  10.     //  Inside Caller, after calling the method, the first element is: 888
  11.     // ==============================================================
  12.     static void SendArrayByVal() {
  13.       int[] arr = { 1, 4, 5 };
  14.       System.Console.WriteLine("SendArrayByVal()");
  15.       System.Console.WriteLine("Inside Caller, before calling the method, the first element is: {0}", arr[0]);
  16.  
  17.       ModifyArray(arr);
  18.       System.Console.WriteLine("Inside Caller, after calling the method, the first element is : {0}", arr[0]);
  19.     }
  20.     static void ModifyArray(int[] pArray) {
  21.       pArray[0] = 888;  // This change affects the original element.
  22.       pArray = new int[5] { -3, -1, -2, -3, -4 };   // This change is local.
  23.       System.Console.WriteLine("Inside the method, the first element is                       : {0}", pArray[0]);
  24.     }
  25.     // ==============================================================
  26.     // Pass a ref type (class, interface, delegate, object, string) by ref and create a new memory allocation
  27.     //  Inside Caller, before calling the method, the first element is: 1
  28.     //  Inside the method, the first element is: -3
  29.     //  Inside Caller, after calling the method, the first element is: -3    
  30.     // ==============================================================
  31.     static void SendArrayByRef() {
  32.       int[] arr = { 1, 4, 5 };
  33.       System.Console.WriteLine("SendArrayByRef()");
  34.       System.Console.WriteLine("Inside Caller, before calling the method, the first element is: {0}", arr[0]);
  35.  
  36.       ModifyArrayByRef(ref arr);
  37.       System.Console.WriteLine("Inside Caller, after calling the method, the first element is : {0}", arr[0]);
  38.     }
  39.     static void ModifyArrayByRef(ref int[] pArray) {
  40.       pArray[0] = 888;  
  41.       pArray = new int[5] { -3, -1, -2, -3, -4 };  // new memory is allocated to parameter
  42.       System.Console.WriteLine("                       Inside the method, the first element is: {0}", pArray[0]);
  43.     }
  44.  }
  45.  
Oct 17 '08 #3
mldisibio
190 Expert 100+
However, to clarify, insertAlias is correct in this sense: as long as you don't point the [ref varfiles] parameter to a completely new array, then in fact both methods simply modify the original array which is a reference object, and you would observe no difference.

Therefore, except for the specific need to replace the original object with a completely new instance, the ref keyword is not needed for passing objects, and in fact it is more robust NOT to use it, so that you don't expose the original object to accidental "orphanage" or replacement if never intended.

Finally, (for others reading this) remember that in the above explanations "object" means a reference type and not a value type, such as integers and booleans.
Oct 17 '08 #4
Curtis Rutland
3,256 Expert 2GB
Very good explanation.
Oct 17 '08 #5
Frinavale
9,735 Expert Mod 8TB
In the second snippet, you are indeed passing a reference to the array, but reference is an address, equivalent of a pointer. And since the ref keyword is not used, you are sending a copy of that address/pointer. That means, if you "point" the pointer to a new object/address/array, the original pointer remains intact and continues to point to the original array.
Thanks for that clarification! I had forgotten this bit of information.


For a bit more information on ByRef and ByVal (in VB.NET) check out this post.

:)

-Frinny
Oct 17 '08 #6
developing
110 100+
In the second snippet, you are indeed passing a reference to the array, but reference is an address, equivalent of a pointer. And since the ref keyword is not used, you are sending a copy of that address/pointer. That means, if you "point" the pointer to a new object/address/array, the original pointer remains intact and continues to point to the original array.

That's what I came up with except I didn't know how to test it.

For the two snippets above, I wasn't really concerned about the end result of the function, just wanted to see the "inner workings" because yeah, both will return a char[] except the first snippet doesn't really need to.


Thanks for all the replies and clearing that up!
Oct 20 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) {...
5
by: Andy | last post by:
Hi Could someone clarify for me the method parameter passing concept? As I understand it, if you pass a variable without the "ref" syntax then it gets passed as a copy. If you pass a...
26
by: Dave Hammond | last post by:
In document "A.html" I have defined a function and within the document body have included an IFRAME element who's source is document "B.html". In document "B.html" I am trying to call the function...
39
by: Mike MacSween | last post by:
Just spent a happy 10 mins trying to understand a function I wrote sometime ago. Then remembered that arguments are passed by reference, by default. Does the fact that this slowed me down...
8
by: Dennis Myrén | last post by:
I have these tiny classes, implementing an interface through which their method Render ( CosWriter writer ) ; is called. Given a specific context, there are potentially a lot of such objects,...
13
by: Maxim | last post by:
Hi! A have a string variable (which is a reference type). Now I define my Method like that: void MakeFullName(string sNamePrivate) { sNamePrivate+="Gates" }
8
by: Johnny | last post by:
I'm a rookie at C# and OO so please don't laugh! I have a form (fclsTaxCalculator) that contains a text box (tboxZipCode) containing a zip code. The user can enter a zip code in the text box and...
6
by: MSDNAndi | last post by:
Hi, I get the following warning: "Possibly incorrect assignment to local 'oLockObject' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the...
10
by: amazon | last post by:
Our vender provided us a web service: 1xyztest.xsd file... ------------------------------------ postEvent PostEventRequest ------------------------------------- authetication authentication...
7
by: TS | last post by:
I was under the assumption that if you pass an object as a param to a method and inside that method this object is changed, the object will stay changed when returned from the method because the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.