When you pass a variable using ref
, you are asserting that the variable is already initialized (even if that value is null
for reference types). It's no different to declaring it as a local variable and then trying to use it in the same method without initializing it. This is why you can't pass uninitialized variables. There's also the problem that, even if this were possible, you would have no means of telling whether or not it has been initialized in code.
As to why passing it doesn't simply initialize it to default(type)
, I couldn't possibly say. My feeling is that it makes sense that it doesn't, and that you should be explicit in the code you write, so initializing the variable beforehand makes sense.
So that you can use uninitialized variables, out
exists. So to fix your code, replace ref
with out
. It's now the repsonsibility of SomeMethod
to initialize i
:
public static void main()
{
int i;
SomeMethod(out i);
}
public static void SomeMethod(out int i)
{
i = 10;
}
Further reading: