Why can't I pass an unassigned object variable to the out parameter and then assign it

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

If I try to do this, a compiler error occurs: "A local variable <xyz>cannot be declared in this scope, because it will have a different value for <xyz>..."

eg.

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

EDIT: Now I see my mistake. I changed the above code to what I had. MyObjectin stars should not be.

+3
source share
4 answers

The code you posted 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();
}

mo, "" mo.

, : -)

+4

, mo - . , :

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

MyObject mo;

, , , .

+2

out ( #)

out . ref, , ref , . out, out.

, , , .

So this should be fine, except that your method syntax is incorrect. To separate parameters, you need to use a comma, not a colon.

+1
source

Given your actual code, you cannot define mo since it is already defined as an out parameter

0
source

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


All Articles