-3

Getting error use of unassigned out parameter 'q' and 'g', please correct where I am doing wrong. Thanks in advance.

using System;  
using System.Collections.Generic;
using System.Linq;
using System.Text;  
using System.Threading.Tasks;   

class Program  
{  
    static void Main(string[] args)  
    {  
        int p = 23;  
        int f = 24;  
        Fun(out p, out f);  
        Console.WriteLine("{0} {1}", p, f);  

    }  
    static void Fun(out int q, out int g)  
    {  
        q = q+1;  
        g = g+1;  
    }  
}  
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Maddy
  • 3
  • 3
  • 4
    Sounds like you need to go read the documentation for `out`. You don't seem to understand what it does. – Servy Oct 31 '14 at 18:09

1 Answers1

9

What you're doing wrong is exactly what the compiler says you're doing wrong - you're trying to read from an out parameter before it's definitely assigned. Look at your code:

static void Fun(out int q, out int g)  
{  
    q = q + 1;  
    g = g + 1;  
}  

In each case, the right hand side of the assignment expression uses an out parameter, and that out parameter hasn't been given a value yet. out parameters are initially not definitely assigned, and must be definitely assigned before the method returns (other than via an exception)

If the idea is to increment both parameters, you should use ref instead.

static void Fun(ref int q, ref int g)  
{  
    q = q + 1;  
    g = g + 1;  
}  

Or more simply:

static void Fun(ref int q, ref int g)  
{  
    q++;
    g++;
}  

You'll need to change the calling code to:

Fun(ref p, ref f);
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • That means I can't do it with out parameter? – Maddy Oct 31 '14 at 18:16
  • 1
    @Maddy: Well you can't do anything that requires the value of the parameter before it's assigned within the method, no. Bear in mind that you could have written `int p, f; Fun(out p, out f);` - what would you have expected the values to be in that case? – Jon Skeet Oct 31 '14 at 18:17
  • The same Answer as I got from your method however i was trying to get it with the help op OUT parameter... – Maddy Oct 31 '14 at 18:24
  • @Maddy: *Why*? You're trying to use `out` parameters for something that they're explicitly not designed for... they're called `out` because data comes *out* via them, rather than *in*. – Jon Skeet Oct 31 '14 at 18:29