Out parameter in c#

Total Post:22

Points:154
C# 
C#
 2061  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. 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
    }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
    }

      Modified On Mar-31-2018 04:25:44 AM

Answer