I have seen new feature in C# 6 which allows code to skip if
statements for null
checks.
For example:
return p?.ToString();
How can this be done for calling a method to which p
needs to be passed as parameter (without old if
/else
)?
The way I would normally write this with C# pre-6:
p != null ? callmethod(p) : null
is there something better in C# 6?
String data types are often initalized to null as well. However, for the exact same reasons, we prefer to use an empty string to replace null .
So, to return a null or default value from a generic method we can make use default(). default(T) will return the default object of the type which is provided.
Empty(A constant for empty strings). This method will take a parameter that will be of System. String type. The method will return a Boolean value, like n case if the argument String type has null or empty string (“”), then it will return True value else it will return False value.
Throwing an exception is another common alternative in the Java API to returning a null when, for any reason, a value can't be provided. A typical example of this is the conversion of String into an int , provided by the Integer.
You can use an extension method - which you can generalize to any situation. This works because C# allows extension methods to work with null
values for the this
parameter (surprisingly!), whereas with normal instance methods you would otherwise get a NullReferenceException
.
Here's something similar to what I used in my own projects before we had the ?.
"safe-navigation" operator in C# 6:
public static class Extensions
{
public static TRet NullSafeCall<TValue,TRet>( this TValue value, Func<TValue,TRet> func )
where TValue : class
where TRet : class
{
if( value != null ) return func( value );
return null;
}
}
Used like so:
return p.NullSafeCall( callmethod );
It also supports the use of lambdas if you need to pass more than 1 argument into your subsequent func
:
String foo = "bar";
return p.NullSafeCall( v => callmethod2( v, foo ) );
In your example you used String.IsNullOrEmpty
instead of != null
, which can be added like so:
public static class Extensions
{
public static TRet NullSafeCall<TValue,TRet>( this TValue value, Func<TValue,Boolean> guard, Func<TValue,TRet> func )
where TValue : class
where TRet : class
{
if( guard( value ) ) return func( value );
return null;
}
}
Usage:
return p.NullSafeCall( v => String.IsNullOrEmpty( v ), v => callmethod( v ) );
And of course, you can chain it:
return p
.NullSafeCall( callmethod2 )
.NullSafeCall( callmethod3 )
.NullSafeCall( v => callmethod4( v, "foo", bar ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With