Method with parameter ref ref

Hi, I need to call a method that has this signature:

int MethodName(ref object vIndexKey) 

If I try to call it with

 String c = "690"; MethodName(ref (object) c); 

This does not work.

How can i do this?

thanks

+4
source share
3 answers

You need to do it like this:

 String c = "690"; object o = (object) c; MethodName(ref o); 

The reason is that the parameter must be assigned by the function. A function could do something like this:

 o = new List<int>(); 

This is not possible if the base type is a string that was passed to the object during the method call, since the destination will still be a string, not an object.

+10
source

When a method has a ref parameter, the type of the argument must exactly match the type of the parameter. Suppose MethodName were implemented as follows:

 public void MethodName(ref object x) { x = new object(); } 

What would you expect if you could only call it with ref c ? He would try to write a reference to a simple System.Object to a variable of type System.String , thereby violating type safety.

So you need to have a variable of type object . You can do this as shown in klausbyskov's answer, but keep in mind that the value will not then be copied back to the original variable. You can do this with a throw, but remember that it can fail:

 string c = "690"; object o = c; MethodName(ref o); // This will fail if `MethodName` has set the parameter value to a non-null // non-string reference c = (string) o; 

Here is the corresponding bit of the C # 3.0 specification, section 10.6.1.2 (emphasis mine):

When a formal parameter is a parameter reference, the corresponding argument in the method call should consist of the ref keyword, followed by the reference variable (ยง5.3.3) of the same type as the formal parameter . A variable must be definitely assigned before it can be passed as a reference parameter.

+2
source

Whether there is a

 MethodName(ref c); 

does not work?

-1
source

Source: https://habr.com/ru/post/1301806/


All Articles