Null propagating operator in C# 6.0

Something I’ve been wanting for years in .Net (c# specifically) is a cleaner way to detect null objects before trying to access properties or methonds on said objects. Just today I noticed that C# 6.0 (along with Visual Studio 2014) will finally make this a bit easier. 

In the past, before you access a property on an object, you would want to make sure it’s not null first. So instead of doing: 

var val = myobject.myValue; 

You would want to add null checking code like this: 

 

if(myObject != null){

   var val = myObject.myValue; 

}

Multiply this code by thousands of times, and it becomes a huge headache to look at, maintain, or even test. 

So: Null propagation operator (or, null propagating operator) to the rescue. We can replace the “.” with a “?.” operator to have the system check the object for null prior to accessing a property. So our c# 6.0 version of the above will now look like this: 

var val = myObject?.myValue; 

val will take on the type of myValue, or rather, a nullable version of the type of myValue. So if myValue is an int, val will be an int?. 

We can also combine this with the null coalescing operator to provide a default value, and keep val as a normal int:

var val = myObject?.myValue ?? 0; 

Looking forward to using this in future projects. 

Send email from .Net – MAPI

You need to send an email from your thick client .Net app (winforms or WPF), but don’t want to mess with using MailMessage and configuring it to use a remote server etc.

Instead, you can use MAPI and just pop open a new message using your default installed email client (often outlook, but any mapi compliant email client will work).

This article on codeproject gives excellent coverage of this topic http://www.codeproject.com/Articles/17561/Programmatically-adding-attachments-to-emails-in-C

Beware that this is a good thing to use for occasional emails, not for heavy sending. MAPI has some known issues with memory management when called via interop from .Net, so if you make heavy use of it you will likely crash.

Also, since MAPI only works with locally installed email clients, it will not work with a web based one (ie, gmail).