Handling out variables in C# 7.0

Most of you will be familiar with “out” variables in C#. They are often misused to return multiple values from a function and can indicate a code smell.

Nevertheless they exist and 7.0 provides some new syntax in this area.

Here’s a typical example from the well-known built-in TryParse function from before C# 7.0:

public void OldWay()
{
	int number;
	if (int.TryParse("1234", out number))
	{
		Console.WriteLine(number);
	}
}

We instantiate “number”, pass it to TryParse and it will be populated with 1234 if the parse succeeds.

C# 7 saves us from the necessity of declaring a variable up front in the following way:

public void NewWay()
{
	//include out param in expression
	if (int.TryParse("1234", out int number)) //works with "var" as well as with the concrete object type
	{
		Console.WriteLine(number);
	}
	Console.WriteLine(number);
}

So we declare “number” in an expression and it will be available outside the “if” block as well.

If parsing fails then the declared variable will get a default value. Numbers get 0, reference types “null” etc.

View all various C# language feature related posts here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: