I’m looking for a clear, concise and accurate answer.
Ideally as the actual answer, although links to good explanations welcome.
This also applies to VB.Net, but the keywords are different – ByRef and ByVal.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
By default (in C#), passing an object to a function actually passes a copy of the reference to that object. Changing the parameter itself only changes the value in the parameter, and not the variable that was specified.
Using
outorrefpasses a reference to the variable specified in the call to the function. Any changes to the value of anoutorrefparameter will be passed back to the caller.Both
outandrefbehave identically except for one slight difference:refparameters are required to be initialised before calling, whileoutparameters can be uninitialised. By extension,refparameters are guaranteed to be initialised at the start of the method, whileoutparameters are treated as uninitialised.Edit: As dp points out, the difference between
outandrefis only enforced by the C# compiler, not by the CLR. As far as I know, VB has no equivalent foroutand implementsref(asByRef) only, matching the support of the CLR.