Home > DeveloperSection > Forums > Out parameter in c#
Madam Walker
Madam Walker

Total Post:22

Points:154
Posted on    September-28-2013 8:51 AM

 C# C# 
Ratings:


 1 Reply(s)
 1261  View(s)
Rate this:
I am new to C#. I've tried this with out parameter in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class First
{
    public void fun(out int m)
    {
        m *= 10;
        Console.WriteLine("value of m = " + m);
    }
}
class Program
{
    static void Main(string[] args)
    {
        First f = new First();
        int x = 30;
        f.fun(out x);
    }
}

but i get some errors like "Use of unassigned out parameter 'm'" and
The out parameter 'm' must be assigned to before control leaves the current method.

So what is the meaning of these errors and why it is compulsory to assign 'm' when i'm already assigned a value to x.



ben reitman
ben reitman

Total Post:96

Points:676
Posted on    September-28-2013 9:09 AM

Hello Madam!
public void Ref_Test(ref int x)
{
    var y = x; // ok
    x = 10;
}
// x is treated as an unitialized variable
public void Out_Test(out int x)
{
    var y = x; // not ok (will not compile)
}
public void Out_Test2(out int x)
{
    x = 10;
    var y = x; // ok because x is initialized in the line above
}

Don't want to miss updates? Please click the below button!

Follow MindStick