So we have ternary operators. Great! Then there's the ??
operator, which does a coalesce over a nullable
variable.
Example:
string emptyIfNull = strValue ?? "";
Question: Is it possible to implement a simple operator like this for a try-catch?
Example:
string result = CoalesceException(someExpression, "");
public static T CoalesceException<T>(expression, defaultValue)
{
try
{
return evaluate expression; // ?
}
catch
{
return defaultValue;
}
}
Is it possible to implement a method that can be used as easily as possible, or even some kind of coalesce-like operator?
You can:
public static T CoalesceException<T>(Func<T> func, T defaultValue = default(T))
{
try
{
return func();
}
catch
{
return defaultValue;
}
}
but I'm not sure this is what you want...
use:
string emptyIfError = CoalesceException(() => someExpressionThatReturnsAString, "");
for example...
string shortString = null;
string emptyIfError = CoalesceException(() => shortString.Substring(10), "");
will return ""
instead of NullReferenceException
important
The function, as written, will cause the "evaluation" of defaultValue
always. Meaning:
string Throws() { throw new Exception(); }
string str1 = somethingTrue == true ? "Foo" : Throws();
Here an exception won't be thrown, because Throws()
won't be evalued. The same happens with the ??
operator.
string str2 = CoalesceException(() => ((string)null).ToString(), Throws());
This will cause an exception before entering in CoalesceException
. Solution:
public static T CoalesceException<T>(Func<T> func, Func<T> defaultValue = null)
{
try
{
return func();
}
catch
{
return defaultValue != null ? defaultValue() : default(T);
}
}
Use:
string emptyIfError = CoalesceException(() => someExpressionThatReturnsAString, () => "");
Here a little something that I've end up, to create a One Liner TryCatch
Usage
var r = Task.TryCatch(() => _logic.Method01(param1, param2));
TryCatch definition
public static class Task
{
public static TResult TryCatch<TResult>(Func<TResult> methodDelegate)
{
try
{
return methodDelegate();
}
catch (Exception ex)
{
// .. exception handling ...
}
return default(TResult);
}
}
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