-1

while am trying with ref keyword by replacing out key word there is no error in the below code.while am trying to use out instead of ref there occur an error like"Unassigned OUT Parameter" What does this error mean ?

   static void Main()
    {
        string test = "34";
        addOneToRefParam(out test);
        Console.WriteLine("test is : " + test);
    }

    public static void addOneToRefParam(out string i)
    {
        int  k =Convert.ToInt32(i) + 1;
        i = Convert.ToString(k);
        Console.WriteLine("i is : " + i);
    }
MMM
  • 3,132
  • 3
  • 20
  • 32
  • 9
    I wish there was a searchenginge which could find answers to questions like this. I bet the URL would look like this https://www.google.com/search?q=csharp+ref+out – DerApe Sep 02 '14 at 08:43
  • 3
    @derape that's an impressive UI mockup, too; kudos. Someone should make that. – Marc Gravell Sep 02 '14 at 08:43
  • Minor aside: as far as the CLI is concerned: "absolutely nothing". There is precisely zero difference between `ref` and `out`, except that one happens to have an attribute on it that it isn't interested in. All differences here are *entirely* at the compiler level. – Marc Gravell Sep 02 '14 at 08:45
  • Also: http://stackoverflow.com/questions/388464/whats-the-difference-between-the-ref-and-out-keywords – Marc Gravell Sep 02 '14 at 08:46
  • 1
    You neither need `ref` since you don't modify it nor `out` since you need it as input parameter. You just want `string i`. – Tim Schmelter Sep 02 '14 at 08:46
  • http://stackoverflow.com/questions/388464/whats-the-difference-between-the-ref-and-out-keywords http://stackoverflow.com/questions/1516876/when-to-use-ref-vs-out – Amit Soni Sep 02 '14 at 08:46

1 Answers1

2

ref parameters must be initialized before passing to function,the parameter may or may not be changed by the function.So you need to initialize it before you pass, like you do with non-ref arguments:

int i; 
Foo(i); // error unassigned variable
Foo(ref i) // same error

For out, your function guarantees that it will set the argument to a value.So it doesn't need to be initialized.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184