views:

95

answers:

5

In C#, why can't I pass an unassigned object variable in an out parameter and then assign it?

If I try to do this, there is a compiler error: "Local variable <xyz> cannot be declared in this scope because it would give a different meaning to <xyz>..."

eg.

void MyMethod(int x, out MyObject mo) {  **MyObject** mo = new MyObject(); }
// in some other scope:
MyObject mo;
MyMethod(1, out mo);

EDIT: I can see my mistake now. I have changed the above code to what mine was. The MyObject in asterisks should not be there.

+1  A: 

From the documentation

out (C# Reference)

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

So it should be fine, except that your method syntax is incorrect. You need to use a comma instead of a semi colon to seperate parameters.

astander
A: 

instead of out use ref keyword. out is used when memory is assigned inside a method. ref is used when memory is assigned outside the method.

Nitin Chaudhari
I've already said this many times, but the code he posted **works**. There is something that he hasn't told us about that is causing the error.
Dean Harding
+2  A: 

This error message means that there is another variable named mo somewhere in the same method. For example, such code would cause this error:

for( int mo = 0; i < 5; i++ ) Console.WriteLine( mo );

MyObject mo;

You probably didn't think it was related, so you didn't post the whole code.

Fyodor Soikin
A: 

Given your actual code, you cannot define mo because it's already defined as an out parameter

Carlos Muñoz
+3  A: 

The code you posted original was incorrect, but now we see that the problem is actually here:

void MyMethod(int x, out MyObject mo)
{
    MyObject mo = new MyObject();
    // should be:
    // mo = new MyObject();
}

You're creating a new local variable mo which "hides" the parameter mo.

Glad we got there in the end :-)

Dean Harding