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);
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.
source share