Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to force a parameter to be passed by value instead of ref in C# like you can in VB?

Tags:

c#

vb.net

Having just answered a question about calling VB6 methods with parentheses, I remembered that you could force ByRef parameter values to be passed ByVal. Researching, I found this still works in VB.NET.

However, I cannot find anything similar in C# that allows for this. This past year I have had to reference a lot of VB.NET class libraries that take in ByRef for no good reason (trust me, I checked). This has forced me to set properties on objects to local variables in order to pass them in. Not a major issue, but not very clean if you ask me.

I am wondering if there is a syntactical solution that I am not aware of.

As an example of my current pattern that I would like to avoid:

var tempSomeObject = BarObject.FooProperty;
SomeVb6BusinessLogicMethod(ref tempSomeObject);
// Continue to do work and set other temp objects due to ref constraint

In VB6 and VB.NET, you can just do the following to force ByVal on a ByRef parameter.

SomeVb6BusinessLogicMethod((BarObject.FooProperty)) 'Note the extra parens

EDIT: I am not asking about the differences between ByRef and ByVal. I am asking if C# has a similar way to force a ByRef parameter to be pass ByVal. See this MSDN doc of the VB.NET functionality. http://msdn.microsoft.com/en-us/library/chy4288y.aspx

like image 415
TyCobb Avatar asked Oct 09 '14 17:10

TyCobb


People also ask

Does C pass by reference or value?

C always uses 'pass by value' to pass arguments to functions (another term is 'call by value', which means the same thing), which means the code within a function cannot alter the arguments used to call the function, even if the values are changed inside the function.

Is parameter passed by value or reference?

Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that's why it's called pass by value. Pass by Reference: An alias or reference to the actual parameter is passed to the method, that's why it's called pass by reference.

Can I pass a value as a parameter?

You can pass values to the parameters that are declared in the AccessProfile widget by reference, by value, or by specifying the direct value. Define this option in the main AccessProfile. This topic provides an example of an AccessProfile widget and a main AccessProfile.

Does C# always pass reference?

In C#, arguments can be passed to parameters either by value or by reference.


1 Answers

You will need to explicitly copy the value to a new variable and pass in the new variable by reference, as you showed in your question. There is no syntactic sugar in C# that would allow the compiler to perform this copy on your behalf as is done in VB.

like image 178
Servy Avatar answered Oct 03 '22 19:10

Servy