Use of unassigned out parameter 'q'

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
people
quotationmark

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);

people

See more on this question at Stackoverflow