OUT PARAMETER IN C#

Madam Walker

Total Post:22

Points:154
Posted by  Madam Walker
C# 
C#
 1647  View(s)
Ratings:
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.

  1. ben reitman

    Post:96

    Points:676
    Re: Out parameter in c#

    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
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!