tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

C# 6 refactoring

8 Jan 2016 1 mins C#, Programming in general

Speaking last year on MS Fest in Prague about C# 6 I got feedback I showed all the features in funny way and mostly in edge cases which were far from real world usage. And kind of questioning the usefulness of the features.

And I probably did. I tried to show the feature and also abuse it a little. So to show the features are actually useful in real world, here’s a refactoring I did yesterday evening on a few lines of code. The code was fine. But with C# 6 it’s even more fine (I think).

The original version looked like this.

catch (HttpRequestException ex)
{
	var webEx = ex.InnerException as WebException;
	if (webEx != null)
	{
		var httpWR = webEx.Response as HttpWebResponse;
		return httpWR != null
			? Tuple.Create((HttpStatusCode?)httpWR.StatusCode, (string)null)
			: Tuple.Create((HttpStatusCode?)null, (string)null);
	}
	throw;
}

The catch block is part of helper method used in tests to do some HTTP requests and get values back. While working around (and that actually started the refactoring) I was able to change it to the following code while keeping the result same (OK, the rethrowing is not there as it’s not needed).

catch (HttpRequestException ex) when (ex.InnerException is WebException)
{
	var response = ((WebException)ex.InnerException).Response as HttpWebResponse;
	return Tuple.Create(response?.StatusCode, (string)null);
}

I think this is great example. It’s shorter, more “ordered”, sort of, and thus more readable. What do you think?

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.