X

C# tip: out parameter keyword

dotnet C#

In C# there is the out parameter keyword which causes arguments to be passed by reference. It is like the ref keyword, except that ref requires that the variable be initialized before it is passed.

Example:


void Init(out int x)
{
 x = 47;
}

int x;

Init(out x);

Console.WriteLine(x); //x now is 47

The out parameter keyword provides a way for a method to output multiple values from a method without using an array or object, since the return statement only allows one output, by using out one can return multiple values.


bool HasComma(string str, out string data)
{
	if(str.Contains(','))
	{
	  int index = str.LastIndexOf(',') + 1;	  
	  data = str.Substring(index);
	  return true;
	}
	
	data = string.Empty;
	return false;
}

string d;
bool containsComma = HasComma("a,B",out  d);
Console.WriteLine(d); //d is now the string B containsComma is true
	
containsComma = HasComma("ab",out  d); //d is string.Empty and containsComma is false

int a, b, c, d, e;
bool isTrue = Method(out a, out b, out c, out d, out e); // bad method.

Last but not least I personally do not recommend using out keyword and also from
The Framework Design Guidelines it also recommend to avoid using out. If you have multiple returns use an object that wraps around the value is a better design.

Categories: .NET C#
Taswar Bhatti:
Related Post