Null-Conditional Operator in C# 6.0

If you’ve read blog posts or even MSDN articles explaining new features in C# 6.0 – I’m sure you’ve learned that the null-conditional operator in C# 6.0 will help you to greatly reduce the number of hard-to-debug and hard-to-reproduce NullReferenceException-s.

When I first read about this operator, the only thing that registered in my mind was that it helped you to chain null checks, especially for descending into data structures, and short-circuit the rest of the checks as soon as you hit null somewhere in the chain. So, I thought it was just a mere convenient syntactic sugar.

But I still did not completely understood the true power of this operator. I’m usually pretty meticulous about null checks and have a lot of C# 5.0 code like this:

private static int GetCurrentSpeed(Car car)
{
	if (car != null && car.Engine != null && car.Engine.ControlUnit != null)
	{
		return car.Engine.ControlUnit.CurrentSpeed;
	}

	return 0;
}

And I was debating whether it was worth it to go through the code base and refactor it to use null-conditional operator. Would I gain anything? Was it worth it just to have the code to look like this:

private static int GetCurrentSpeed(Car car)
{
	return car?.Engine?.ControlUnit?.CurrentSpeed ?? 0;
}

Okay, I cut 5 lines of code, what’s the big deal?

Continue reading “Null-Conditional Operator in C# 6.0”

Null-Conditional Operator in C# 6.0

Better Functional Programming Support Is Coming In C# 7

I have recently listened to .NET Rocks! episode #1272 Looking into C# 7 with Kathleen Dollard where she mentioned that the next version of C# will have better support for tuples, immutability, records and pattern matching. You can download the episode and fast forward to 27:04 and 30:04 respectively. If you are interested, you can review the C# 7 Work List of Features (revision circa March 24 2016). You can familiarize yourself with support for these features in C# 7 right now, but since it is pretty much still work in progress, by the time it hits CTP or even release – there is a big chance it will look different.

So, what can you do in the meantime? Fortunately, Visual Studio ships with F# and you can start learning above mentioned Functional Programming concepts right now. Remember, F# is just another CLR language as C# is and many features like Generics and support for async/await came to C# from F#. When it comes to Functional Programming I hope this trend will continue.

Continue reading “Better Functional Programming Support Is Coming In C# 7”

Better Functional Programming Support Is Coming In C# 7