- Back to Home »
- .NET , C#.NET »
- C#.NET ref and out parameters with example
Posted by :
Sudhir Chekuri
Tuesday, 31 May 2016
ref stands for reference and out stands for output.
ref parameter variable should be initialized before we call the method. That value will be used a as reference value in the method.
out parameter variable initialization is not required but it should be returned by the method.
Example program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FirstConsole
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
//val1 has to be initialized
int val1 = 10;
p.Add(ref val1);
//val2 initialization not required
int val2;
int j = p.Sub(out val2);
Console.WriteLine(j);
Console.ReadKey();
}
public void Add(ref int val1)
{ //code goes here
Console.WriteLine("Hello");
}
public int Sub(out int val2)
{
//val2 is changed from 2 to 5
val2 = 5;
return val2;
}
}
}
ref parameter variable should be initialized before we call the method. That value will be used a as reference value in the method.
out parameter variable initialization is not required but it should be returned by the method.
Example program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FirstConsole
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
//val1 has to be initialized
int val1 = 10;
p.Add(ref val1);
//val2 initialization not required
int val2;
int j = p.Sub(out val2);
Console.WriteLine(j);
Console.ReadKey();
}
public void Add(ref int val1)
{ //code goes here
Console.WriteLine("Hello");
}
public int Sub(out int val2)
{
//val2 is changed from 2 to 5
val2 = 5;
return val2;
}
}
}
Output:
Hello