Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i am getting an error Argument 2 may not be passed with ref keyword while using ado.net

int? t = 0;
cmd.Parameters.AddWithValue("@Res", ref t);

I get an error in the second line:

argument 2 may not be passed with ref keyword.

like image 652
Varnika gupta Avatar asked Jan 21 '17 09:01

Varnika gupta


People also ask

What is ref keyword in C#?

The ref keyword indicates that a value is passed by reference. It is used in four different contexts: In a method signature and in a method call, to pass an argument to a method by reference. For more information, see Passing an argument by reference. In a method signature, to return a value to the caller by reference.

How do you pass a value by reference in C#?

Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference with the intent of changing the value, use the ref , or out keyword.

Is object passed by reference C#?

By default, C# does not allow you to choose whether to pass each argument by value or by reference. Value types are passed by value. Objects are not passed to methods; rather, references to objects are passed—the references themselves are passed by value.


1 Answers

You can only pass an argument by reference with ref if the parameter is a ref parameter as well. AddWithValue doesn't have any ref parameters, so you can't use it that way. Note that you have to specify ref when calling a method if a parameter has the ref modifier. So:

public void WithRef(ref int x) {}
public void WithoutRef(int x) {}

...


int y = 0;
// Valid
WithRef(ref y);
WithoutRef(y);
// Invalid
WithRef(y);
WithoutRef(ref y);

Basically, there's no way of telling an ADO.NET command parameter to track the current value of a variable - after all, that variable could be a local variable which will be "gone" by the time you use the command.

Instead, just compute the right value and then set it for the parameter value.

like image 161
Jon Skeet Avatar answered Oct 14 '22 21:10

Jon Skeet