variable trouble!

J

Jeff

Hey

The code below generates this compile error:
Use of unassigned out parameter 'x'

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
public static void A(out int x)
{
Console.WriteLine(x);
x = 1;
}

public static int Main(string[] args)
{
int y = 3;
A(out y);
return 0;
}
}
}

I don't understand why I get that error. In Main I give y the value 3, then
I send y into A... y becomes x in A so it should work.... but no don't
work.. I get this compile error mention above....

Is it so that a parameter sent (using out) into a method always must be
given a value before it can be used in the method? That sounds very unlikely
to me.. but then again I'm just trying to learn C# :)

I would appreciate if some of you could give a comment on why I get that
compile error!

Jeff
 
S

Scott M.

The problem is this line:

Console.WriteLine(x);

Because out parameters are NOT required to be initialized prior to being
passed (the only difference between out and ref parameters is that ref
parameters ARE required to be initialized before being passed), there is a
chance that your "x" variable won't have been initialized when you hit your
Console.WriteLine(x); statement.
 
J

Jon Shemitz

Scott M. said:
(the only difference between out and ref parameters is that ref
parameters ARE required to be initialized before being passed)

Not quite - out parameters, like results, must be set in all execution
paths through the method. Ref parameters don't have to be set.
 
S

Scott M.

Right, I was getting my initialize and my assign confused. The problem with
the OP's code is as I stated though (the Definate Assignment Rule).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top