Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing arguments by reference 1

Status
Not open for further replies.

IlyaRabyy

Programmer
Nov 9, 2010
568
US
Colleagues,
Correct me if I'm wrong: in the signature/call like this

Code:
SomeFunction(int iArg1, string cStr1, ref int iArg2, string cStr2)

the both (or any, for that matter) arguments after the "ref" are passed by reference - correct?

TIA!

On the footnote: I can't recall, neither find anywhere, where I've seen this rule, that any argument after "ref" is passed by reference... or I'm mixing it up with "Optional" in VB? Acute case of CRS. :-(
"With aging, eyesight is 2nd thing to go, and I can't recall what the 1st one is..." :)

Regards,

Ilya
 
If you want your function (SomeFunction) to modify the value of a parameter, each parameter you want to modify needs to have the ref qualifier.

In your example, you can modify the values for iArg2 and cStr2 within the function, but once the function is returned to the caller, cStr2 will have it's original value. I tested this with:

Code:
        static void Main(string[] args)
        {
            int iArg1 = 0;
            string cStr1 = "Red";
            int iArg2 = 1;
            string cStr2 = "Green";

            SomeFunction(iArg1, cStr1, ref iArg2, cStr2);
            Console.WriteLine("iArg2: " + iArg2.ToString());
            Console.WriteLine("cStr2: " + cStr2);
        }

        private static void SomeFunction(int iArg1, string cStr1, ref int iArg2, string cStr2)
        {
            iArg2 = 3;
            cStr2 = "Four";
        }

cStr2 does not have the ref qualifier. Inside the function, it's value is changed to "Four", but in the Console.WriteLine, you will see that it's value is "Green".


-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Right!
Mix it with "Optional" in VB did I (Sorry, Master [yoda]! )

:)

Like I've said: acute case of CRS! [blush]
Thank you, colleague!

Regards,

Ilya
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top