Saturday, December 17, 2016

Nice news in c#7


C#7 is coming together with Visual Studio 2017 and here is my two favorite news.

Throw Exception

It’s a common thing to control your input parameters to prevent future reference null exceptions before you assign it to a field like this:
if (person == null)
{ throw new ArgumentException("Person can't be null"); }
_person = person;
But now you can do it like this:
_person = person ?? throw new ArgumentException("Person can't be null");

Out variables

When we use a function that demands an out variable it’s common that half the times we don’t even care about that value when the function returns, but we do have to be nice and declare that variable before calling that function. Like this::
int i;
var isNumber = int.TryParse(s, out i);
Now i c#7 we can declare inside the function call:
var isNumber = int.TryParse(s, out int i);

No comments:

Post a Comment