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.
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 :-)