Coalescing with ReSharper 3.0
The ReSharper 3.0 beta is out and I'm really digging it. It's little things that make my day a better place.
For example I had a piece of code that looked like this:
14 public ErrorReportProxy(IWebProxy proxy, bool needProcessEvents)
15 {
16 _errorReport.Proxy = proxy;
17 if (proxy.Credentials != null) _errorReport.Proxy.Credentials = proxy.Credentials;
18 else _errorReport.Proxy.Credentials = CredentialCache.DefaultCredentials;
19 _needProcessEvents = needProcessEvents;
20 }
"if" statements are so 1990s so you can rewrite it like this using the conditional operator "?"
14 public ErrorReportProxy(IWebProxy proxy, bool needProcessEvents)
15 {
16 _errorReport.Proxy = proxy;
17 _errorReport.Proxy.Credentials = (proxy.Credentials != null)
18 ? proxy.Credentials
19 : CredentialCache.DefaultCredentials;
20 _needProcessEvents = needProcessEvents;
21 }
However with nullable types in C# 2.0 you can use the language feature of using the "??" assignment (called the null coalesce operator). The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. This shortens the code but makes it more readable (at least to me).
ReShaper to the rescue as it showed me squiggly lines in my code where I had the "?" operator and said (in a nice ReSharper way not an evil Clippy way):
'?:' expression could be re-written as '??' expression.
So a quick ALT+ENTER and the code becomes this:
14 public ErrorReportProxy(IWebProxy proxy, bool needProcessEvents)
15 {
16 _errorReport.Proxy = proxy;
17 _errorReport.Proxy.Credentials = proxy.Credentials ?? CredentialCache.DefaultCredentials;
18 _needProcessEvents = needProcessEvents;
19 }
Okay, so maybe I'm easily amused but it's the little things that make my day (and maybe yours) a little brighter. The coding assistance feature of ReSharper 3.0 is shaping up to be very useful indeed.