Declare Out variable right at the point – Out variable in C# 7.0

Declare Out variable right at the point – Out variable in C# 7.0

In C#, we often used Out parameter,  as like call by reference, mostly when we want to return multiple values from a method. Whenever we call a method with an Out parameter, we must have to declare that variable first, before we use it.  Now, with C# 7.0, we can directly declare the Out Variable and you don’t need to initialize it separately.

Consider the following example, where we have used the Out as a parameter for the tempText, and We have initialized it first before we pass it as Out Parameter.

static void Main(string[] args)
{
string tempText;
TestMethod(out tempText);
}

static void TestMethod(out string strName)
{
strName = "Out variable";
}

Now, in C# 7.0, declare it right at the point when you need it. As shown in the below example, TestMethod() call made with direct declaration of an out variable.

static void Main(string[] args)
{
TestMethod(out string tempText);
}

static void TestMethod(out string strName)
{
strName = "Out variable";
}

At this point of time, If you try to initialize the ‘tempText’, you will get following error – “A local variable or function named ‘tempText’ is already defined in the scope.”

C# 7.0 Tips : Directly throw Exception as an Expression – Throw expressions in C# 7.0

We have all seen, one of the very frequent uses of the Out parameter was Converts the string representation of a number. With the help of out variable, now we can directly declare like below.

bool success = int.TryParse(Console.ReadLine(), out int result);

Related Post : Back to Basic : Difference Between int.Parse() and int.TryParse()

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

2 Comments to “Declare Out variable right at the point – Out variable in C# 7.0”

Comments are closed.